feat: Implement autocomplete feature with enhanced UI and tooltip support

- Added AutoComplete class to handle input suggestions based on user input.
- Integrated TextAreaCaretHelper for accurate positioning of the dropdown.
- Enhanced dropdown styling with a new color scheme and custom scrollbar.
- Implemented dynamic loading of preview tooltips for selected items.
- Added keyboard navigation support for dropdown items.
- Included functionality to insert selected items into the input field with usage tips.
- Created a separate TextAreaCaretHelper module for managing caret position calculations.
This commit is contained in:
Will Miao
2025-08-16 07:53:55 +08:00
parent ed1cd39a6c
commit 6a281cf3ee
12 changed files with 1674 additions and 16 deletions

View File

@@ -68,6 +68,9 @@ class BaseModelRoutes(ABC):
app.router.add_get(f'/api/{prefix}/get-notes', self.get_model_notes)
app.router.add_get(f'/api/{prefix}/preview-url', self.get_model_preview_url)
app.router.add_get(f'/api/{prefix}/civitai-url', self.get_model_civitai_url)
# Autocomplete route
app.router.add_get(f'/api/{prefix}/relative-paths', self.get_relative_paths)
# Common Download management
app.router.add_post(f'/api/download-model', self.download_model)
@@ -1058,6 +1061,26 @@ class BaseModelRoutes(ABC):
except Exception as e:
logger.error(f"Error getting {self.model_type} Civitai URL: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
async def get_relative_paths(self, request: web.Request) -> web.Response:
"""Get model relative file paths for autocomplete functionality"""
try:
search = request.query.get('search', '').strip()
limit = min(int(request.query.get('limit', '15')), 50) # Max 50 items
matching_paths = await self.service.search_relative_paths(search, limit)
return web.json_response({
'success': True,
'relative_paths': matching_paths
})
except Exception as e:
logger.error(f"Error getting relative paths for autocomplete: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)

View File

@@ -45,6 +45,7 @@ class LoraRoutes(BaseModelRoutes):
app.router.add_get(f'/api/{prefix}/letter-counts', self.get_letter_counts)
app.router.add_get(f'/api/{prefix}/get-trigger-words', self.get_lora_trigger_words)
app.router.add_get(f'/api/{prefix}/model-description', self.get_lora_model_description)
app.router.add_get(f'/api/{prefix}/usage-tips-by-path', self.get_lora_usage_tips_by_path)
# CivitAI integration with LoRA-specific validation
app.router.add_get(f'/api/{prefix}/civitai/versions/{{model_id}}', self.get_civitai_versions_lora)
@@ -140,6 +141,26 @@ class LoraRoutes(BaseModelRoutes):
'error': str(e)
}, status=500)
async def get_lora_usage_tips_by_path(self, request: web.Request) -> web.Response:
"""Get usage tips for a LoRA by its relative path"""
try:
relative_path = request.query.get('relative_path')
if not relative_path:
return web.Response(text='Relative path is required', status=400)
usage_tips = await self.service.get_lora_usage_tips_by_relative_path(relative_path)
return web.json_response({
'success': True,
'usage_tips': usage_tips or ''
})
except Exception as e:
logger.error(f"Error getting lora usage tips by path: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
async def get_lora_preview_url(self, request: web.Request) -> web.Response:
"""Get the static preview URL for a LoRA file"""
try:

View File

@@ -1,6 +1,7 @@
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Type
import logging
import os
from ..utils.models import BaseModelMetadata
from ..utils.constants import NSFW_LEVELS
@@ -376,4 +377,46 @@ class BaseModelService(ABC):
'version_id': str(version_id) if version_id else None
}
return {'civitai_url': None, 'model_id': None, 'version_id': None}
return {'civitai_url': None, 'model_id': None, 'version_id': None}
async def search_relative_paths(self, search_term: str, limit: int = 15) -> List[str]:
"""Search model relative file paths for autocomplete functionality"""
cache = await self.scanner.get_cached_data()
matching_paths = []
search_lower = search_term.lower()
# Get model roots for path calculation
model_roots = self.scanner.get_model_roots()
for model in cache.raw_data:
file_path = model.get('file_path', '')
if not file_path:
continue
# Calculate relative path from model root
relative_path = None
for root in model_roots:
# Normalize paths for comparison
normalized_root = os.path.normpath(root).replace(os.sep, '/')
normalized_file = os.path.normpath(file_path).replace(os.sep, '/')
if normalized_file.startswith(normalized_root):
# Remove root and leading slash to get relative path
relative_path = normalized_file[len(normalized_root):].lstrip('/')
break
if relative_path and search_lower in relative_path.lower():
matching_paths.append(relative_path)
if len(matching_paths) >= limit * 2: # Get more for better sorting
break
# Sort by relevance (exact matches first, then by length)
matching_paths.sort(key=lambda x: (
not x.lower().startswith(search_lower), # Exact prefix matches first
len(x), # Then by length (shorter first)
x.lower() # Then alphabetically
))
return matching_paths[:limit]

View File

@@ -158,6 +158,21 @@ class LoraService(BaseModelService):
return []
async def get_lora_usage_tips_by_relative_path(self, relative_path: str) -> Optional[str]:
"""Get usage tips for a LoRA by its relative path"""
cache = await self.scanner.get_cached_data()
for lora in cache.raw_data:
file_path = lora.get('file_path', '')
if file_path:
# Convert to forward slashes and extract relative path
file_path_normalized = file_path.replace('\\', '/')
# Find the relative path part by looking for the relative_path in the full path
if file_path_normalized.endswith(relative_path) or relative_path in file_path_normalized:
return lora.get('usage_tips', '')
return None
def find_duplicate_hashes(self) -> Dict:
"""Find LoRAs with duplicate SHA256 hashes"""
return self.scanner._hash_index.get_duplicate_hashes()

689
refs/style.css Normal file
View File

@@ -0,0 +1,689 @@
@layer primevue, tailwind-utilities;
@layer tailwind-utilities {
@tailwind components;
@tailwind utilities;
}
:root {
--fg-color: #000;
--bg-color: #fff;
--comfy-menu-bg: #353535;
--comfy-menu-secondary-bg: #292929;
--comfy-topbar-height: 2.5rem;
--comfy-input-bg: #222;
--input-text: #ddd;
--descrip-text: #999;
--drag-text: #ccc;
--error-text: #ff4444;
--border-color: #4e4e4e;
--tr-even-bg-color: #222;
--tr-odd-bg-color: #353535;
--primary-bg: #236692;
--primary-fg: #ffffff;
--primary-hover-bg: #3485bb;
--primary-hover-fg: #ffffff;
--content-bg: #e0e0e0;
--content-fg: #000;
--content-hover-bg: #adadad;
--content-hover-fg: #000;
}
@media (prefers-color-scheme: dark) {
:root {
--fg-color: #fff;
--bg-color: #202020;
--content-bg: #4e4e4e;
--content-fg: #fff;
--content-hover-bg: #222;
--content-hover-fg: #fff;
}
}
body {
width: 100vw;
height: 100vh;
margin: 0;
overflow: hidden;
background: var(--bg-color) var(--bg-img);
color: var(--fg-color);
min-height: -webkit-fill-available;
max-height: -webkit-fill-available;
min-width: -webkit-fill-available;
max-width: -webkit-fill-available;
font-family: Arial, sans-serif;
}
.comfy-multiline-input {
background-color: var(--comfy-input-bg);
color: var(--input-text);
overflow: hidden;
overflow-y: auto;
padding: 2px;
resize: none;
border: none;
box-sizing: border-box;
font-size: var(--comfy-textarea-font-size);
}
.comfy-markdown {
/* We assign the textarea and the Tiptap editor to the same CSS grid area to stack them on top of one another. */
display: grid;
}
.comfy-markdown > textarea {
grid-area: 1 / 1 / 2 / 2;
}
.comfy-markdown .tiptap {
grid-area: 1 / 1 / 2 / 2;
background-color: var(--comfy-input-bg);
color: var(--input-text);
overflow: hidden;
overflow-y: auto;
resize: none;
border: none;
box-sizing: border-box;
font-size: var(--comfy-textarea-font-size);
height: 100%;
padding: 0.5em;
}
.comfy-markdown.editing .tiptap {
display: none;
}
.comfy-markdown .tiptap :first-child {
margin-top: 0;
}
.comfy-markdown .tiptap :last-child {
margin-bottom: 0;
}
.comfy-markdown .tiptap blockquote {
border-left: medium solid;
margin-left: 1em;
padding-left: 0.5em;
}
.comfy-markdown .tiptap pre {
border: thin dotted;
border-radius: 0.5em;
margin: 0.5em;
padding: 0.5em;
}
.comfy-markdown .tiptap table {
border-collapse: collapse;
}
.comfy-markdown .tiptap th {
text-align: left;
background: var(--comfy-menu-bg);
}
.comfy-markdown .tiptap th,
.comfy-markdown .tiptap td {
padding: 0.5em;
border: thin solid;
}
.comfy-modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 100; /* Sit on top */
padding: 30px 30px 10px 30px;
background-color: var(--comfy-menu-bg); /* Modal background */
color: var(--error-text);
box-shadow: 0 0 20px #888888;
border-radius: 10px;
top: 50%;
left: 50%;
max-width: 80vw;
max-height: 80vh;
transform: translate(-50%, -50%);
overflow: hidden;
justify-content: center;
font-family: monospace;
font-size: 15px;
}
.comfy-modal-content {
display: flex;
flex-direction: column;
}
.comfy-modal p {
overflow: auto;
white-space: pre-line; /* This will respect line breaks */
margin-bottom: 20px; /* Add some margin between the text and the close button*/
}
.comfy-modal select,
.comfy-modal input[type='button'],
.comfy-modal input[type='checkbox'] {
margin: 3px 3px 3px 4px;
}
.comfy-menu {
font-size: 15px;
position: absolute;
top: 50%;
right: 0;
text-align: center;
z-index: 999;
width: 190px;
display: flex;
flex-direction: column;
align-items: center;
color: var(--descrip-text);
background-color: var(--comfy-menu-bg);
font-family: sans-serif;
padding: 10px;
border-radius: 0 8px 8px 8px;
box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4);
}
.comfy-menu-header {
display: flex;
}
.comfy-menu-actions {
display: flex;
gap: 3px;
align-items: center;
height: 20px;
position: relative;
top: -1px;
font-size: 22px;
}
.comfy-menu .comfy-menu-actions button {
background-color: rgba(0, 0, 0, 0);
padding: 0;
border: none;
cursor: pointer;
font-size: inherit;
}
.comfy-menu .comfy-menu-actions .comfy-settings-btn {
font-size: 0.6em;
}
button.comfy-close-menu-btn {
font-size: 1em;
line-height: 12px;
color: #ccc;
position: relative;
top: -1px;
}
.comfy-menu-queue-size {
flex: auto;
}
.comfy-menu button,
.comfy-modal button {
font-size: 20px;
}
.comfy-menu-btns {
margin-bottom: 10px;
width: 100%;
}
.comfy-menu-btns button {
font-size: 10px;
width: 50%;
color: var(--descrip-text) !important;
}
.comfy-menu > button {
width: 100%;
}
.comfy-btn,
.comfy-menu > button,
.comfy-menu-btns button,
.comfy-menu .comfy-list button,
.comfy-modal button {
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-radius: 8px;
border-color: var(--border-color);
border-style: solid;
margin-top: 2px;
}
.comfy-btn:hover:not(:disabled),
.comfy-menu > button:hover,
.comfy-menu-btns button:hover,
.comfy-menu .comfy-list button:hover,
.comfy-modal button:hover,
.comfy-menu-actions button:hover {
filter: brightness(1.2);
will-change: transform;
cursor: pointer;
}
span.drag-handle {
width: 10px;
height: 20px;
display: inline-block;
overflow: hidden;
line-height: 5px;
padding: 3px 4px;
cursor: move;
vertical-align: middle;
margin-top: -0.4em;
margin-left: -0.2em;
font-size: 12px;
font-family: sans-serif;
letter-spacing: 2px;
color: var(--drag-text);
text-shadow: 1px 0 1px black;
touch-action: none;
}
span.drag-handle::after {
content: '.. .. ..';
}
.comfy-queue-btn {
width: 100%;
}
.comfy-list {
color: var(--descrip-text);
background-color: var(--comfy-menu-bg);
margin-bottom: 10px;
border-color: var(--border-color);
border-style: solid;
}
.comfy-list-items {
overflow-y: scroll;
max-height: 100px;
min-height: 25px;
background-color: var(--comfy-input-bg);
padding: 5px;
}
.comfy-list h4 {
min-width: 160px;
margin: 0;
padding: 3px;
font-weight: normal;
}
.comfy-list-items button {
font-size: 10px;
}
.comfy-list-actions {
margin: 5px;
display: flex;
gap: 5px;
justify-content: center;
}
.comfy-list-actions button {
font-size: 12px;
}
button.comfy-queue-btn {
margin: 6px 0 !important;
}
.comfy-modal.comfy-settings,
.comfy-modal.comfy-manage-templates {
text-align: center;
font-family: sans-serif;
color: var(--descrip-text);
z-index: 99;
}
.comfy-modal.comfy-settings input[type='range'] {
vertical-align: middle;
}
.comfy-modal.comfy-settings input[type='range'] + input[type='number'] {
width: 3.5em;
}
.comfy-modal input,
.comfy-modal select {
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-radius: 8px;
border-color: var(--border-color);
border-style: solid;
font-size: inherit;
}
.comfy-tooltip-indicator {
text-decoration: underline;
text-decoration-style: dashed;
}
@media only screen and (max-height: 850px) {
.comfy-menu {
top: 0 !important;
bottom: 0 !important;
left: auto !important;
right: 0 !important;
border-radius: 0;
}
.comfy-menu span.drag-handle {
display: none;
}
.comfy-menu-queue-size {
flex: unset;
}
.comfy-menu-header {
justify-content: space-between;
}
.comfy-menu-actions {
gap: 10px;
font-size: 28px;
}
}
/* Input popup */
.graphdialog {
min-height: 1em;
background-color: var(--comfy-menu-bg);
z-index: 41; /* z-index is set to 41 here in order to appear over selection-overlay-container which should have a z-index of 40 */
}
.graphdialog .name {
font-size: 14px;
font-family: sans-serif;
color: var(--descrip-text);
}
.graphdialog button {
margin-top: unset;
vertical-align: unset;
height: 1.6em;
padding-right: 8px;
}
.graphdialog input,
.graphdialog textarea,
.graphdialog select {
background-color: var(--comfy-input-bg);
border: 2px solid;
border-color: var(--border-color);
color: var(--input-text);
border-radius: 12px 0 0 12px;
}
/* Dialogs */
dialog {
box-shadow: 0 0 20px #888888;
}
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
}
.comfy-dialog.comfyui-dialog.comfy-modal {
top: 0;
left: 0;
right: 0;
bottom: 0;
transform: none;
}
.comfy-dialog.comfy-modal {
font-family: Arial, sans-serif;
border-color: var(--bg-color);
box-shadow: none;
border: 2px solid var(--border-color);
}
.comfy-dialog .comfy-modal-content {
flex-direction: row;
flex-wrap: wrap;
gap: 10px;
color: var(--fg-color);
}
.comfy-dialog .comfy-modal-content h3 {
margin-top: 0;
}
.comfy-dialog .comfy-modal-content > p {
width: 100%;
}
.comfy-dialog .comfy-modal-content > .comfyui-button {
flex: 1;
justify-content: center;
}
/* Context menu */
.litegraph .dialog {
z-index: 1;
font-family: Arial, sans-serif;
}
.litegraph .litemenu-entry.has_submenu {
position: relative;
padding-right: 20px;
}
.litemenu-entry.has_submenu::after {
content: '>';
position: absolute;
top: 0;
right: 2px;
}
.litegraph.litecontextmenu,
.litegraph.litecontextmenu.dark {
z-index: 9999 !important;
background-color: var(--comfy-menu-bg) !important;
}
.litegraph.litecontextmenu
.litemenu-entry:hover:not(.disabled):not(.separator) {
background-color: var(--comfy-menu-hover-bg, var(--border-color)) !important;
color: var(--fg-color);
}
.litegraph.litecontextmenu .litemenu-entry.submenu,
.litegraph.litecontextmenu.dark .litemenu-entry.submenu {
background-color: var(--comfy-menu-bg) !important;
color: var(--input-text);
}
.litegraph.litecontextmenu input {
background-color: var(--comfy-input-bg) !important;
color: var(--input-text) !important;
}
.comfy-context-menu-filter {
box-sizing: border-box;
border: 1px solid #999;
margin: 0 0 5px 5px;
width: calc(100% - 10px);
}
.comfy-img-preview {
pointer-events: none;
overflow: hidden;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
justify-content: center;
}
.comfy-img-preview img {
object-fit: contain;
width: var(--comfy-img-preview-width);
height: var(--comfy-img-preview-height);
}
.comfy-img-preview video {
pointer-events: auto;
object-fit: contain;
height: 100%;
width: 100%;
}
.comfy-missing-nodes li button {
font-size: 12px;
margin-left: 5px;
}
/* Search box */
.litegraph.litesearchbox {
z-index: 9999 !important;
background-color: var(--comfy-menu-bg) !important;
overflow: hidden;
display: block;
}
.litegraph.litesearchbox input,
.litegraph.litesearchbox select {
background-color: var(--comfy-input-bg) !important;
color: var(--input-text);
}
.litegraph.lite-search-item {
color: var(--input-text);
background-color: var(--comfy-input-bg);
filter: brightness(80%);
will-change: transform;
padding-left: 0.2em;
}
.litegraph.lite-search-item.generic_type {
color: var(--input-text);
filter: brightness(50%);
will-change: transform;
}
audio.comfy-audio.empty-audio-widget {
display: none;
}
#vue-app {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* Set auto complete panel's width as it is not accessible within vue-root */
.p-autocomplete-overlay {
max-width: 25vw;
}
.p-tree-node-content {
padding: var(--comfy-tree-explorer-item-padding) !important;
}
/* Load3d styles */
.comfy-load-3d,
.comfy-load-3d-animation,
.comfy-preview-3d,
.comfy-preview-3d-animation{
display: flex;
flex-direction: column;
background: transparent;
flex: 1;
position: relative;
overflow: hidden;
}
.comfy-load-3d canvas,
.comfy-load-3d-animation canvas,
.comfy-preview-3d canvas,
.comfy-preview-3d-animation canvas{
display: flex;
width: 100% !important;
height: 100% !important;
}
/* End of Load3d styles */
/* [Desktop] Electron window specific styles */
.app-drag {
app-region: drag;
}
.no-drag {
app-region: no-drag;
}
.window-actions-spacer {
width: calc(100vw - env(titlebar-area-width, 100vw));
}
/* End of [Desktop] Electron window specific styles */
/* Autocomplete styles */
.comfy-autocomplete-dropdown {
position: absolute;
z-index: 10000;
max-height: 200px;
overflow-y: auto;
background-color: var(--comfy-menu-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
display: none;
font-family: Arial, sans-serif;
font-size: 14px;
min-width: 200px;
}
.comfy-autocomplete-item {
padding: 8px 12px;
cursor: pointer;
color: var(--input-text);
border-bottom: 1px solid var(--border-color);
transition: background-color 0.2s ease;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.comfy-autocomplete-item:last-child {
border-bottom: none;
}
.comfy-autocomplete-item:hover,
.comfy-autocomplete-item-selected {
background-color: var(--comfy-menu-hover-bg, var(--border-color)) !important;
color: var(--input-text);
}
.comfy-autocomplete-dropdown::-webkit-scrollbar {
width: 8px;
}
.comfy-autocomplete-dropdown::-webkit-scrollbar-track {
background: var(--comfy-input-bg);
border-radius: 4px;
}
.comfy-autocomplete-dropdown::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 4px;
}
.comfy-autocomplete-dropdown::-webkit-scrollbar-thumb:hover {
background: var(--descrip-text);
}

452
web/comfyui/autocomplete.js Normal file
View File

@@ -0,0 +1,452 @@
import { api } from "../../scripts/api.js";
import { app } from "../../scripts/app.js";
import { TextAreaCaretHelper } from "./textarea_caret_helper.js";
class AutoComplete {
constructor(inputElement, modelType = 'loras', options = {}) {
this.inputElement = inputElement;
this.modelType = modelType;
this.options = {
maxItems: 15,
minChars: 1,
debounceDelay: 200,
showPreview: true,
...options
};
this.dropdown = null;
this.selectedIndex = -1;
this.items = [];
this.debounceTimer = null;
this.isVisible = false;
this.currentSearchTerm = '';
this.previewTooltip = null;
// Initialize TextAreaCaretHelper
this.helper = new TextAreaCaretHelper(inputElement, () => app.canvas.ds.scale);
this.init();
}
init() {
this.createDropdown();
this.bindEvents();
}
createDropdown() {
this.dropdown = document.createElement('div');
this.dropdown.className = 'comfy-autocomplete-dropdown';
// Apply new color scheme
this.dropdown.style.cssText = `
position: absolute;
z-index: 10000;
overflow-y: visible;
background-color: rgba(40, 44, 52, 0.95);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
display: none;
font-family: Arial, sans-serif;
font-size: 14px;
min-width: 200px;
width: auto;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
`;
// Custom scrollbar styles with new color scheme
const style = document.createElement('style');
style.textContent = `
.comfy-autocomplete-dropdown::-webkit-scrollbar {
width: 8px;
}
.comfy-autocomplete-dropdown::-webkit-scrollbar-track {
background: rgba(40, 44, 52, 0.3);
border-radius: 4px;
}
.comfy-autocomplete-dropdown::-webkit-scrollbar-thumb {
background: rgba(226, 232, 240, 0.2);
border-radius: 4px;
}
.comfy-autocomplete-dropdown::-webkit-scrollbar-thumb:hover {
background: rgba(226, 232, 240, 0.4);
}
`;
document.head.appendChild(style);
// Append to body to avoid overflow issues
document.body.appendChild(this.dropdown);
// Initialize preview tooltip if needed
if (this.options.showPreview && this.modelType === 'loras') {
this.initPreviewTooltip();
}
}
initPreviewTooltip() {
// Dynamically import and create preview tooltip
import('./loras_widget_components.js').then(module => {
this.previewTooltip = new module.PreviewTooltip();
}).catch(err => {
console.warn('Failed to load preview tooltip:', err);
});
}
bindEvents() {
// Handle input changes
this.inputElement.addEventListener('input', (e) => {
this.handleInput(e.target.value);
});
// Handle keyboard navigation
this.inputElement.addEventListener('keydown', (e) => {
this.handleKeyDown(e);
});
// Handle focus out to hide dropdown
this.inputElement.addEventListener('blur', (e) => {
// Delay hiding to allow for clicks on dropdown items
setTimeout(() => {
this.hide();
}, 150);
});
// Handle clicks outside to hide dropdown
document.addEventListener('click', (e) => {
if (!this.dropdown.contains(e.target) && e.target !== this.inputElement) {
this.hide();
}
});
}
handleInput(value = '') {
// Clear previous debounce timer
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
// Get the search term (text after last comma)
const searchTerm = this.getSearchTerm(value);
if (searchTerm.length < this.options.minChars) {
this.hide();
return;
}
// Debounce the search
this.debounceTimer = setTimeout(() => {
this.search(searchTerm);
}, this.options.debounceDelay);
}
getSearchTerm(value) {
const lastCommaIndex = value.lastIndexOf(',');
if (lastCommaIndex === -1) {
return value.trim();
}
return value.substring(lastCommaIndex + 1).trim();
}
async search(term = '') {
try {
this.currentSearchTerm = term;
const response = await api.fetchApi(`/${this.modelType}/relative-paths?search=${encodeURIComponent(term)}&limit=${this.options.maxItems}`);
const data = await response.json();
if (data.success && data.relative_paths && data.relative_paths.length > 0) {
this.items = data.relative_paths;
this.render();
this.show();
} else {
this.items = [];
this.hide();
}
} catch (error) {
console.error('Autocomplete search error:', error);
this.items = [];
this.hide();
}
}
render() {
this.dropdown.innerHTML = '';
this.selectedIndex = -1;
// Early return if no items to prevent empty dropdown
if (!this.items || this.items.length === 0) {
return;
}
this.items.forEach((relativePath, index) => {
const item = document.createElement('div');
item.className = 'comfy-autocomplete-item';
// Create highlighted content
const highlightedContent = this.highlightMatch(relativePath, this.currentSearchTerm);
item.innerHTML = highlightedContent;
// Apply item styles with new color scheme
item.style.cssText = `
padding: 8px 12px;
cursor: pointer;
color: rgba(226, 232, 240, 0.8);
border-bottom: 1px solid rgba(226, 232, 240, 0.1);
transition: all 0.2s ease;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
position: relative;
`;
// Hover and selection handlers
item.addEventListener('mouseenter', () => {
this.selectItem(index);
this.showPreviewForItem(relativePath, item);
});
item.addEventListener('mouseleave', () => {
this.hidePreview();
});
// Click handler
item.addEventListener('click', () => {
this.insertSelection(relativePath);
});
this.dropdown.appendChild(item);
});
// Remove border from last item
if (this.dropdown.lastChild) {
this.dropdown.lastChild.style.borderBottom = 'none';
}
}
highlightMatch(text, searchTerm) {
if (!searchTerm) return text;
const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
return text.replace(regex, '<span style="background-color: rgba(66, 153, 225, 0.3); color: white; padding: 1px 2px; border-radius: 2px;">$1</span>');
}
showPreviewForItem(relativePath, itemElement) {
if (!this.previewTooltip) return;
// Extract filename without extension for preview
const fileName = relativePath.split('/').pop();
const loraName = fileName.replace(/\.(safetensors|ckpt|pt|bin)$/i, '');
// Get item position for tooltip positioning
const rect = itemElement.getBoundingClientRect();
const x = rect.right + 10;
const y = rect.top;
this.previewTooltip.show(loraName, x, y);
}
hidePreview() {
if (this.previewTooltip) {
this.previewTooltip.hide();
}
}
show() {
if (!this.items || this.items.length === 0) {
this.hide();
return;
}
// Position dropdown at cursor position using TextAreaCaretHelper
this.positionAtCursor();
this.dropdown.style.display = 'block';
this.isVisible = true;
}
positionAtCursor() {
const position = this.helper.getCursorOffset();
this.dropdown.style.left = (position.left ?? 0) + "px";
this.dropdown.style.top = (position.top ?? 0) + "px";
this.dropdown.style.maxHeight = (window.innerHeight - position.top) + "px";
// Adjust width to fit content
// Temporarily show the dropdown to measure content width
const originalDisplay = this.dropdown.style.display;
this.dropdown.style.display = 'block';
this.dropdown.style.visibility = 'hidden';
// Measure the content width
let maxWidth = 200; // minimum width
const items = this.dropdown.querySelectorAll('.comfy-autocomplete-item');
items.forEach(item => {
const itemWidth = item.scrollWidth + 24; // Add padding
maxWidth = Math.max(maxWidth, itemWidth);
});
// Set the width and restore visibility
this.dropdown.style.width = Math.min(maxWidth, 400) + 'px'; // Cap at 400px
this.dropdown.style.visibility = 'visible';
this.dropdown.style.display = originalDisplay;
}
getCaretPosition() {
return this.inputElement.selectionStart || 0;
}
hide() {
this.dropdown.style.display = 'none';
this.isVisible = false;
this.selectedIndex = -1;
// Hide preview tooltip
this.hidePreview();
// Clear selection styles from all items
const items = this.dropdown.querySelectorAll('.comfy-autocomplete-item');
items.forEach(item => {
item.classList.remove('comfy-autocomplete-item-selected');
item.style.backgroundColor = '';
});
}
selectItem(index) {
// Remove previous selection
const prevSelected = this.dropdown.querySelector('.comfy-autocomplete-item-selected');
if (prevSelected) {
prevSelected.classList.remove('comfy-autocomplete-item-selected');
prevSelected.style.backgroundColor = '';
}
// Add new selection
if (index >= 0 && index < this.items.length) {
this.selectedIndex = index;
const item = this.dropdown.children[index];
item.classList.add('comfy-autocomplete-item-selected');
item.style.backgroundColor = 'rgba(66, 153, 225, 0.2)';
// Scroll into view if needed
item.scrollIntoView({ block: 'nearest' });
// Show preview for selected item
if (this.options.showPreview) {
this.showPreviewForItem(this.items[index], item);
}
}
}
handleKeyDown(e) {
if (!this.isVisible) {
return;
}
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
this.selectItem(Math.min(this.selectedIndex + 1, this.items.length - 1));
break;
case 'ArrowUp':
e.preventDefault();
this.selectItem(Math.max(this.selectedIndex - 1, 0));
break;
case 'Enter':
e.preventDefault();
if (this.selectedIndex >= 0 && this.selectedIndex < this.items.length) {
this.insertSelection(this.items[this.selectedIndex]);
}
break;
case 'Escape':
e.preventDefault();
this.hide();
break;
}
}
async insertSelection(relativePath) {
// Extract just the filename for LoRA name
const fileName = relativePath.split('/').pop().replace(/\.(safetensors|ckpt|pt|bin)$/i, '');
// Get usage tips and extract strength
let strength = 1.0; // Default strength
try {
const response = await api.fetchApi(`/loras/usage-tips-by-path?relative_path=${encodeURIComponent(relativePath)}`);
if (response.ok) {
const data = await response.json();
if (data.success && data.usage_tips) {
// Parse JSON string and extract strength
try {
const usageTips = JSON.parse(data.usage_tips);
if (usageTips.strength && typeof usageTips.strength === 'number') {
strength = usageTips.strength;
}
} catch (parseError) {
console.warn('Failed to parse usage tips JSON:', parseError);
}
}
}
} catch (error) {
console.warn('Failed to fetch usage tips:', error);
}
// Format the LoRA code with strength
const loraCode = `<lora:${fileName}:${strength}>, `;
const currentValue = this.inputElement.value;
const caretPos = this.getCaretPosition();
const lastCommaIndex = currentValue.lastIndexOf(',', caretPos - 1);
let newValue;
let newCaretPos;
if (lastCommaIndex === -1) {
// No comma found before cursor, replace from start or current search term start
const searchTerm = this.getSearchTerm(currentValue.substring(0, caretPos));
const searchStartPos = caretPos - searchTerm.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;
// Trigger input event to notify about the change
const event = new Event('input', { bubbles: true });
this.inputElement.dispatchEvent(event);
this.hide();
// Focus back to input and position cursor
this.inputElement.focus();
this.inputElement.setSelectionRange(newCaretPos, newCaretPos);
}
destroy() {
if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
if (this.previewTooltip) {
this.previewTooltip.cleanup();
}
if (this.dropdown && this.dropdown.parentNode) {
this.dropdown.parentNode.removeChild(this.dropdown);
}
// Remove event listeners would be added here if we tracked them
}
}
export { AutoComplete };

View File

@@ -5,7 +5,8 @@ import {
collectActiveLorasFromChain,
updateConnectedTriggerWords,
chainCallback,
mergeLoras
mergeLoras,
setupInputWidgetWithAutocomplete
} from "./utils.js";
import { addLorasWidget } from "./loras_widget.js";
@@ -158,7 +159,8 @@ app.registerExtension({
const inputWidget = this.widgets[0];
inputWidget.options.getMaxHeight = () => 100;
this.inputWidget = inputWidget;
inputWidget.callback = (value) => {
const originalCallback = (value) => {
if (isUpdating) return;
isUpdating = true;
@@ -172,6 +174,9 @@ app.registerExtension({
}
};
// Setup input widget with autocomplete
inputWidget.callback = setupInputWidgetWithAutocomplete(this, inputWidget, originalCallback);
// Register this node with the backend
this.registerNode = async () => {
try {

View File

@@ -5,7 +5,8 @@ import {
collectActiveLorasFromChain,
updateConnectedTriggerWords,
chainCallback,
mergeLoras
mergeLoras,
setupInputWidgetWithAutocomplete
} from "./utils.js";
import { addLorasWidget } from "./loras_widget.js";
@@ -79,7 +80,8 @@ app.registerExtension({
const inputWidget = this.widgets[0];
inputWidget.options.getMaxHeight = () => 100;
this.inputWidget = inputWidget;
inputWidget.callback = (value) => {
// Wrap the callback with autocomplete setup
const originalCallback = (value) => {
if (isUpdating) return;
isUpdating = true;
@@ -99,6 +101,7 @@ app.registerExtension({
isUpdating = false;
}
};
inputWidget.callback = setupInputWidgetWithAutocomplete(this, inputWidget, originalCallback);
// Register this node with the backend
this.registerNode = async () => {

View File

@@ -219,18 +219,26 @@ export class PreviewTooltip {
display: 'none',
overflow: 'hidden',
maxWidth: '300px',
pointerEvents: 'none', // Prevent interference with autocomplete
});
document.body.appendChild(this.element);
this.hideTimeout = null;
this.isFromAutocomplete = false;
// Add global click event to hide tooltip
document.addEventListener('click', () => this.hide());
// Modified event listeners for autocomplete compatibility
this.globalClickHandler = (e) => {
// Don't hide if click is on autocomplete dropdown
if (!e.target.closest('.comfy-autocomplete-dropdown')) {
this.hide();
}
};
document.addEventListener('click', this.globalClickHandler);
// Add scroll event listener
document.addEventListener('scroll', () => this.hide(), true);
this.globalScrollHandler = () => this.hide();
document.addEventListener('scroll', this.globalScrollHandler, true);
}
async show(loraName, x, y) {
async show(loraName, x, y, fromAutocomplete = false) {
try {
// Clear previous hide timer
if (this.hideTimeout) {
@@ -238,8 +246,12 @@ export class PreviewTooltip {
this.hideTimeout = null;
}
// Track if this is from autocomplete
this.isFromAutocomplete = fromAutocomplete;
// Don't redisplay the same lora preview
if (this.element.style.display === 'block' && this.currentLora === loraName) {
this.position(x, y);
return;
}
@@ -300,7 +312,7 @@ export class PreviewTooltip {
left: '0',
right: '0',
padding: '8px',
color: 'rgba(255, 255, 255, 0.95)',
color: 'white',
fontSize: '13px',
fontFamily: "'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif",
background: 'linear-gradient(transparent, rgba(0, 0, 0, 0.8))',
@@ -349,6 +361,10 @@ export class PreviewTooltip {
top = y - rect.height - 10;
}
// Ensure minimum distance from edges
left = Math.max(10, Math.min(left, viewportWidth - rect.width - 10));
top = Math.max(10, Math.min(top, viewportHeight - rect.height - 10));
Object.assign(this.element.style, {
left: `${left}px`,
top: `${top}px`
@@ -362,6 +378,7 @@ export class PreviewTooltip {
this.hideTimeout = setTimeout(() => {
this.element.style.display = 'none';
this.currentLora = null;
this.isFromAutocomplete = false;
// Stop video playback
const video = this.element.querySelector('video');
if (video) {
@@ -376,9 +393,9 @@ export class PreviewTooltip {
if (this.hideTimeout) {
clearTimeout(this.hideTimeout);
}
// Remove all event listeners
document.removeEventListener('click', () => this.hide());
document.removeEventListener('scroll', () => this.hide(), true);
// Remove event listeners properly
document.removeEventListener('click', this.globalClickHandler);
document.removeEventListener('scroll', this.globalScrollHandler, true);
this.element.remove();
}
}

View File

@@ -0,0 +1,332 @@
/*
https://github.com/component/textarea-caret-position
The MIT License (MIT)
Copyright (c) 2015 Jonathan Ong me@jongleberry.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const getCaretCoordinates = (function () {
// We'll copy the properties below into the mirror div.
// Note that some browsers, such as Firefox, do not concatenate properties
// into their shorthand (e.g. padding-top, padding-bottom etc. -> padding),
// so we have to list every single property explicitly.
var properties = [
"direction", // RTL support
"boxSizing",
"width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does
"height",
"overflowX",
"overflowY", // copy the scrollbar for IE
"borderTopWidth",
"borderRightWidth",
"borderBottomWidth",
"borderLeftWidth",
"borderStyle",
"paddingTop",
"paddingRight",
"paddingBottom",
"paddingLeft",
// https://developer.mozilla.org/en-US/docs/Web/CSS/font
"fontStyle",
"fontVariant",
"fontWeight",
"fontStretch",
"fontSize",
"fontSizeAdjust",
"lineHeight",
"fontFamily",
"textAlign",
"textTransform",
"textIndent",
"textDecoration", // might not make a difference, but better be safe
"letterSpacing",
"wordSpacing",
"tabSize",
"MozTabSize",
];
var isBrowser = typeof window !== "undefined";
var isFirefox = isBrowser && window.mozInnerScreenX != null;
return function getCaretCoordinates(element, position, options) {
if (!isBrowser) {
throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser");
}
var debug = (options && options.debug) || false;
if (debug) {
var el = document.querySelector("#input-textarea-caret-position-mirror-div");
if (el) el.parentNode.removeChild(el);
}
// The mirror div will replicate the textarea's style
var div = document.createElement("div");
div.id = "input-textarea-caret-position-mirror-div";
document.body.appendChild(div);
var style = div.style;
var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9
var isInput = element.nodeName === "INPUT";
// Default textarea styles
style.whiteSpace = "pre-wrap";
if (!isInput) style.wordWrap = "break-word"; // only for textarea-s
// Position off-screen
style.position = "absolute"; // required to return coordinates properly
if (!debug) style.visibility = "hidden"; // not 'display: none' because we want rendering
// Transfer the element's properties to the div
properties.forEach(function (prop) {
if (isInput && prop === "lineHeight") {
// Special case for <input>s because text is rendered centered and line height may be != height
if (computed.boxSizing === "border-box") {
var height = parseInt(computed.height);
var outerHeight =
parseInt(computed.paddingTop) +
parseInt(computed.paddingBottom) +
parseInt(computed.borderTopWidth) +
parseInt(computed.borderBottomWidth);
var targetHeight = outerHeight + parseInt(computed.lineHeight);
if (height > targetHeight) {
style.lineHeight = height - outerHeight + "px";
} else if (height === targetHeight) {
style.lineHeight = computed.lineHeight;
} else {
style.lineHeight = 0;
}
} else {
style.lineHeight = computed.height;
}
} else {
style[prop] = computed[prop];
}
});
if (isFirefox) {
// Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275
if (element.scrollHeight > parseInt(computed.height)) style.overflowY = "scroll";
} else {
style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'
}
div.textContent = element.value.substring(0, position);
// The second special handling for input type="text" vs textarea:
// spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037
if (isInput) div.textContent = div.textContent.replace(/\s/g, "\u00a0");
var span = document.createElement("span");
// Wrapping must be replicated *exactly*, including when a long word gets
// onto the next line, with whitespace at the end of the line before (#7).
// The *only* reliable way to do that is to copy the *entire* rest of the
// textarea's content into the <span> created at the caret position.
// For inputs, just '.' would be enough, but no need to bother.
span.textContent = element.value.substring(position) || "."; // || because a completely empty faux span doesn't render at all
div.appendChild(span);
var coordinates = {
top: span.offsetTop + parseInt(computed["borderTopWidth"]),
left: span.offsetLeft + parseInt(computed["borderLeftWidth"]),
height: parseInt(computed["lineHeight"]),
};
if (debug) {
span.style.backgroundColor = "#aaa";
} else {
document.body.removeChild(div);
}
return coordinates;
};
})();
/*
Key functions from:
https://github.com/yuku/textcomplete
© Yuku Takahashi - This software is licensed under the MIT license.
The MIT License (MIT)
Copyright (c) 2015 Jonathan Ong me@jongleberry.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const CHAR_CODE_ZERO = "0".charCodeAt(0);
const CHAR_CODE_NINE = "9".charCodeAt(0);
export class TextAreaCaretHelper {
constructor(el, getScale) {
this.el = el;
this.getScale = getScale;
}
#calculateElementOffset() {
const rect = this.el.getBoundingClientRect();
const owner = this.el.ownerDocument;
if (owner == null) {
throw new Error("Given element does not belong to document");
}
const { defaultView, documentElement } = owner;
if (defaultView == null) {
throw new Error("Given element does not belong to window");
}
const offset = {
top: rect.top + defaultView.pageYOffset,
left: rect.left + defaultView.pageXOffset,
};
if (documentElement) {
offset.top -= documentElement.clientTop;
offset.left -= documentElement.clientLeft;
}
return offset;
}
#isDigit(charCode) {
return CHAR_CODE_ZERO <= charCode && charCode <= CHAR_CODE_NINE;
}
#getLineHeightPx() {
const computedStyle = getComputedStyle(this.el);
const lineHeight = computedStyle.lineHeight;
// If the char code starts with a digit, it is either a value in pixels,
// or unitless, as per:
// https://drafts.csswg.org/css2/visudet.html#propdef-line-height
// https://drafts.csswg.org/css2/cascade.html#computed-value
if (this.#isDigit(lineHeight.charCodeAt(0))) {
const floatLineHeight = parseFloat(lineHeight);
// In real browsers the value is *always* in pixels, even for unit-less
// line-heights. However, we still check as per the spec.
return this.#isDigit(lineHeight.charCodeAt(lineHeight.length - 1))
? floatLineHeight * parseFloat(computedStyle.fontSize)
: floatLineHeight;
}
// Otherwise, the value is "normal".
// If the line-height is "normal", calculate by font-size
return this.#calculateLineHeightPx(this.el.nodeName, computedStyle);
}
/**
* Returns calculated line-height of the given node in pixels.
*/
#calculateLineHeightPx(nodeName, computedStyle) {
const body = document.body;
if (!body) return 0;
const tempNode = document.createElement(nodeName);
tempNode.innerHTML = "&nbsp;";
Object.assign(tempNode.style, {
fontSize: computedStyle.fontSize,
fontFamily: computedStyle.fontFamily,
padding: "0",
position: "absolute",
});
body.appendChild(tempNode);
// Make sure textarea has only 1 row
if (tempNode instanceof HTMLTextAreaElement) {
tempNode.rows = 1;
}
// Assume the height of the element is the line-height
const height = tempNode.offsetHeight;
body.removeChild(tempNode);
return height;
}
getCursorOffset() {
const scale = this.getScale();
const elOffset = this.#calculateElementOffset();
const elScroll = this.#getElScroll();
const cursorPosition = this.#getCursorPosition();
const lineHeight = this.#getLineHeightPx();
const top = elOffset.top - (elScroll.top * scale) + (cursorPosition.top + lineHeight) * scale;
const left = elOffset.left - elScroll.left + cursorPosition.left;
const clientTop = this.el.getBoundingClientRect().top;
if (this.el.dir !== "rtl") {
return { top, left, lineHeight, clientTop };
} else {
const right = document.documentElement ? document.documentElement.clientWidth - left : 0;
return { top, right, lineHeight, clientTop };
}
}
#getElScroll() {
return { top: this.el.scrollTop, left: this.el.scrollLeft };
}
#getCursorPosition() {
return getCaretCoordinates(this.el, this.el.selectionEnd);
}
getBeforeCursor() {
return this.el.selectionStart !== this.el.selectionEnd ? null : this.el.value.substring(0, this.el.selectionEnd);
}
getAfterCursor() {
return this.el.value.substring(this.el.selectionEnd);
}
insertAtCursor(value, offset, finalOffset) {
if (this.el.selectionStart != null) {
const startPos = this.el.selectionStart;
const endPos = this.el.selectionEnd;
// Move selection to beginning of offset
this.el.selectionStart = this.el.selectionStart + offset;
// Using execCommand to support undo, but since it's officially
// 'deprecated' we need a backup solution, but it won't support undo :(
let pasted = true;
try {
if (!document.execCommand("insertText", false, value)) {
pasted = false;
}
} catch (e) {
console.error("Error caught during execCommand:", e);
pasted = false;
}
if (!pasted) {
console.error(
"execCommand unsuccessful; not supported. Adding text manually, no undo support.");
textarea.setRangeText(modifiedText, this.el.selectionStart, this.el.selectionEnd, 'end');
}
this.el.selectionEnd = this.el.selectionStart = startPos + value.length + offset + (finalOffset ?? 0);
} else {
// Using execCommand to support undo, but since it's officially
// 'deprecated' we need a backup solution, but it won't support undo :(
let pasted = true;
try {
if (!document.execCommand("insertText", false, value)) {
pasted = false;
}
} catch (e) {
console.error("Error caught during execCommand:", e);
pasted = false;
}
if (!pasted) {
console.error(
"execCommand unsuccessful; not supported. Adding text manually, no undo support.");
this.el.value += value;
}
}
}
}

View File

@@ -1,4 +1,5 @@
export const CONVERTED_TYPE = 'converted-widget';
import { AutoComplete } from "./autocomplete.js";
export function chainCallback(object, property, callback) {
if (object == undefined) {
@@ -226,4 +227,58 @@ export function mergeLoras(lorasText, lorasArr) {
}
return result;
}
/**
* Initialize autocomplete for an input widget and setup cleanup
* @param {Object} node - The node instance
* @param {Object} inputWidget - The input widget to add autocomplete to
* @param {Function} originalCallback - The original callback function
* @returns {Function} Enhanced callback function with autocomplete
*/
export function setupInputWidgetWithAutocomplete(node, inputWidget, originalCallback) {
let autocomplete = null;
// Enhanced callback that initializes autocomplete and calls original callback
const enhancedCallback = (value) => {
// Initialize autocomplete on first callback if not already done
if (!autocomplete && inputWidget.inputEl) {
autocomplete = new AutoComplete(inputWidget.inputEl, 'loras', {
maxItems: 15,
minChars: 1,
debounceDelay: 200
});
// Store reference for cleanup
node.autocomplete = autocomplete;
}
// Call the original callback
if (originalCallback) {
originalCallback(value);
}
};
// Setup cleanup on node removal
setupAutocompleteCleanup(node);
return enhancedCallback;
}
/**
* Setup autocomplete cleanup when node is removed
* @param {Object} node - The node instance
*/
export function setupAutocompleteCleanup(node) {
// Override onRemoved to cleanup autocomplete
const originalOnRemoved = node.onRemoved;
node.onRemoved = function() {
if (this.autocomplete) {
this.autocomplete.destroy();
this.autocomplete = null;
}
if (originalOnRemoved) {
originalOnRemoved.call(this);
}
};
}

View File

@@ -4,7 +4,8 @@ import {
getActiveLorasFromNode,
updateConnectedTriggerWords,
chainCallback,
mergeLoras
mergeLoras,
setupInputWidgetWithAutocomplete
} from "./utils.js";
import { addLorasWidget } from "./loras_widget.js";
@@ -80,7 +81,8 @@ app.registerExtension({
const inputWidget = this.widgets[1];
inputWidget.options.getMaxHeight = () => 100;
this.inputWidget = inputWidget;
inputWidget.callback = (value) => {
// Wrap the callback with autocomplete setup
const originalCallback = (value) => {
if (isUpdating) return;
isUpdating = true;
@@ -97,6 +99,7 @@ app.registerExtension({
isUpdating = false;
}
};
inputWidget.callback = setupInputWidgetWithAutocomplete(this, inputWidget, originalCallback);
});
}
},