mirror of
https://github.com/willmiao/ComfyUI-Lora-Manager.git
synced 2026-03-24 06:32:12 -03:00
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:
452
web/comfyui/autocomplete.js
Normal file
452
web/comfyui/autocomplete.js
Normal 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 };
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
332
web/comfyui/textarea_caret_helper.js
Normal file
332
web/comfyui/textarea_caret_helper.js
Normal 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 = " ";
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user