refactor(AutoComplete): simplify search term extraction and insertion logic

This commit is contained in:
Will Miao
2025-09-12 14:35:25 +08:00
parent d5a280cf2b
commit 897787d17c
2 changed files with 19 additions and 34 deletions

View File

@@ -363,7 +363,7 @@ class BaseModelService(ABC):
from ..config import config from ..config import config
return config.get_preview_static_url(preview_url) return config.get_preview_static_url(preview_url)
return None return '/loras_static/images/no-preview.png'
async def get_model_civitai_url(self, model_name: str) -> Dict[str, Optional[str]]: async def get_model_civitai_url(self, model_name: str) -> Dict[str, Optional[str]]:
"""Get the Civitai URL for a model file""" """Get the Civitai URL for a model file"""

View File

@@ -147,8 +147,8 @@ class AutoComplete {
return ''; return '';
} }
// Split on multiple delimiters: comma, space, '>' and other common separators // Split on comma and '>' delimiters only (do not split on spaces)
const segments = beforeCursor.split(/[,\s>]+/); const segments = beforeCursor.split(/[,\>]+/);
// Return the last non-empty segment as search term // Return the last non-empty segment as search term
const lastSegment = segments[segments.length - 1] || ''; const lastSegment = segments[segments.length - 1] || '';
@@ -381,7 +381,7 @@ class AutoComplete {
async insertSelection(relativePath) { async insertSelection(relativePath) {
// Extract just the filename for LoRA name // Extract just the filename for LoRA name
const fileName = relativePath.split(/[/\\]/).pop().replace(/\.(safetensors|ckpt|pt|bin)$/i, ''); const fileName = relativePath.split(/[/\\]/).pop().replace(/\.(safetensors|ckpt|pt|bin)$/i, '');
// Get usage tips and extract strength // Get usage tips and extract strength
let strength = 1.0; // Default strength let strength = 1.0; // Default strength
try { try {
@@ -389,7 +389,6 @@ class AutoComplete {
if (response.ok) { if (response.ok) {
const data = await response.json(); const data = await response.json();
if (data.success && data.usage_tips) { if (data.success && data.usage_tips) {
// Parse JSON string and extract strength
try { try {
const usageTips = JSON.parse(data.usage_tips); const usageTips = JSON.parse(data.usage_tips);
if (usageTips.strength && typeof usageTips.strength === 'number') { if (usageTips.strength && typeof usageTips.strength === 'number') {
@@ -403,44 +402,30 @@ class AutoComplete {
} catch (error) { } catch (error) {
console.warn('Failed to fetch usage tips:', error); console.warn('Failed to fetch usage tips:', error);
} }
// Format the LoRA code with strength // Format the LoRA code with strength
const loraCode = `<lora:${fileName}:${strength}>, `; const loraCode = `<lora:${fileName}:${strength}>, `;
const currentValue = this.inputElement.value; const currentValue = this.inputElement.value;
const caretPos = this.getCaretPosition(); const caretPos = this.getCaretPosition();
const lastCommaIndex = currentValue.lastIndexOf(',', caretPos - 1);
// Use getSearchTerm to get the current search term before cursor
let newValue; const beforeCursor = currentValue.substring(0, caretPos);
let newCaretPos; const searchTerm = this.getSearchTerm(beforeCursor);
const searchStartPos = caretPos - searchTerm.length;
if (lastCommaIndex === -1) {
// No comma found before cursor, replace from start or current search term start // Only replace the search term, not everything after the last comma
const searchTerm = this.getSearchTerm(currentValue.substring(0, caretPos)); const newValue = currentValue.substring(0, searchStartPos) + loraCode + currentValue.substring(caretPos);
const searchStartPos = caretPos - searchTerm.length; const newCaretPos = searchStartPos + loraCode.length;
newValue = currentValue.substring(0, searchStartPos) + loraCode + currentValue.substring(caretPos);
newCaretPos = searchStartPos + loraCode.length;
} else {
// Replace text after last comma before cursor
const afterCommaPos = lastCommaIndex + 1;
// Skip whitespace after comma
let insertPos = afterCommaPos;
while (insertPos < caretPos && /\s/.test(currentValue[insertPos])) {
insertPos++;
}
newValue = currentValue.substring(0, insertPos) + loraCode + currentValue.substring(caretPos);
newCaretPos = insertPos + loraCode.length;
}
this.inputElement.value = newValue; this.inputElement.value = newValue;
// Trigger input event to notify about the change // Trigger input event to notify about the change
const event = new Event('input', { bubbles: true }); const event = new Event('input', { bubbles: true });
this.inputElement.dispatchEvent(event); this.inputElement.dispatchEvent(event);
this.hide(); this.hide();
// Focus back to input and position cursor // Focus back to input and position cursor
this.inputElement.focus(); this.inputElement.focus();
this.inputElement.setSelectionRange(newCaretPos, newCaretPos); this.inputElement.setSelectionRange(newCaretPos, newCaretPos);