feat: add .opencode to gitignore and refactor lora routes

- Add .opencode directory to gitignore for agent-related files
- Refactor lora_routes.py with consistent string formatting and improved route registration
- Add DualRangeSlider Vue component for enhanced UI controls
This commit is contained in:
Will Miao
2026-01-13 13:59:36 +08:00
parent 688baef2f0
commit 1ebd2c93a0
10 changed files with 2793 additions and 662 deletions

3
.gitignore vendored
View File

@@ -12,6 +12,9 @@ coverage/
.coverage
model_cache/
# agent
.opencode/
# Vue widgets development cache (but keep build output)
vue-widgets/node_modules/
vue-widgets/.vite/

View File

@@ -12,14 +12,15 @@ from ..utils.utils import get_lora_info
logger = logging.getLogger(__name__)
class LoraRoutes(BaseModelRoutes):
"""LoRA-specific route controller"""
def __init__(self):
"""Initialize LoRA routes with LoRA service"""
super().__init__()
self.template_name = "loras.html"
async def initialize_services(self):
"""Initialize services from ServiceRegistry"""
lora_scanner = await ServiceRegistry.get_lora_scanner()
@@ -29,231 +30,225 @@ class LoraRoutes(BaseModelRoutes):
# Attach service dependencies
self.attach_service(self.service)
def setup_routes(self, app: web.Application):
"""Setup LoRA routes"""
# Schedule service initialization on app startup
app.on_startup.append(lambda _: self.initialize_services())
# Setup common routes with 'loras' prefix (includes page route)
super().setup_routes(app, 'loras')
super().setup_routes(app, "loras")
def setup_specific_routes(self, registrar: ModelRouteRegistrar, prefix: str):
"""Setup LoRA-specific routes"""
# LoRA-specific query routes
registrar.add_prefixed_route('GET', '/api/lm/{prefix}/letter-counts', prefix, self.get_letter_counts)
registrar.add_prefixed_route('GET', '/api/lm/{prefix}/get-trigger-words', prefix, self.get_lora_trigger_words)
registrar.add_prefixed_route('GET', '/api/lm/{prefix}/usage-tips-by-path', prefix, self.get_lora_usage_tips_by_path)
registrar.add_prefixed_route(
"GET", "/api/lm/{prefix}/letter-counts", prefix, self.get_letter_counts
)
registrar.add_prefixed_route(
"GET",
"/api/lm/{prefix}/get-trigger-words",
prefix,
self.get_lora_trigger_words,
)
registrar.add_prefixed_route(
"GET",
"/api/lm/{prefix}/usage-tips-by-path",
prefix,
self.get_lora_usage_tips_by_path,
)
# Randomizer routes
registrar.add_prefixed_route('POST', '/api/lm/{prefix}/random-sample', prefix, self.get_random_loras)
registrar.add_prefixed_route(
"POST", "/api/lm/{prefix}/random-sample", prefix, self.get_random_loras
)
# ComfyUI integration
registrar.add_prefixed_route('POST', '/api/lm/{prefix}/get_trigger_words', prefix, self.get_trigger_words)
registrar.add_prefixed_route(
"POST", "/api/lm/{prefix}/get_trigger_words", prefix, self.get_trigger_words
)
def _parse_specific_params(self, request: web.Request) -> Dict:
"""Parse LoRA-specific parameters"""
params = {}
# LoRA-specific parameters
if 'first_letter' in request.query:
params['first_letter'] = request.query.get('first_letter')
if "first_letter" in request.query:
params["first_letter"] = request.query.get("first_letter")
# Handle fuzzy search parameter name variation
if request.query.get('fuzzy') == 'true':
params['fuzzy_search'] = True
if request.query.get("fuzzy") == "true":
params["fuzzy_search"] = True
# Handle additional filter parameters for LoRAs
if 'lora_hash' in request.query:
if not params.get('hash_filters'):
params['hash_filters'] = {}
params['hash_filters']['single_hash'] = request.query['lora_hash'].lower()
elif 'lora_hashes' in request.query:
if not params.get('hash_filters'):
params['hash_filters'] = {}
params['hash_filters']['multiple_hashes'] = [h.lower() for h in request.query['lora_hashes'].split(',')]
if "lora_hash" in request.query:
if not params.get("hash_filters"):
params["hash_filters"] = {}
params["hash_filters"]["single_hash"] = request.query["lora_hash"].lower()
elif "lora_hashes" in request.query:
if not params.get("hash_filters"):
params["hash_filters"] = {}
params["hash_filters"]["multiple_hashes"] = [
h.lower() for h in request.query["lora_hashes"].split(",")
]
return params
def _validate_civitai_model_type(self, model_type: str) -> bool:
"""Validate CivitAI model type for LoRA"""
from ..utils.constants import VALID_LORA_TYPES
return model_type.lower() in VALID_LORA_TYPES
def _get_expected_model_types(self) -> str:
"""Get expected model types string for error messages"""
return "LORA, LoCon, or DORA"
# LoRA-specific route handlers
async def get_letter_counts(self, request: web.Request) -> web.Response:
"""Get count of LoRAs for each letter of the alphabet"""
try:
letter_counts = await self.service.get_letter_counts()
return web.json_response({
'success': True,
'letter_counts': letter_counts
})
return web.json_response({"success": True, "letter_counts": letter_counts})
except Exception as e:
logger.error(f"Error getting letter counts: {e}")
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
async def get_lora_notes(self, request: web.Request) -> web.Response:
"""Get notes for a specific LoRA file"""
try:
lora_name = request.query.get('name')
lora_name = request.query.get("name")
if not lora_name:
return web.Response(text='Lora file name is required', status=400)
return web.Response(text="Lora file name is required", status=400)
notes = await self.service.get_lora_notes(lora_name)
if notes is not None:
return web.json_response({
'success': True,
'notes': notes
})
return web.json_response({"success": True, "notes": notes})
else:
return web.json_response({
'success': False,
'error': 'LoRA not found in cache'
}, status=404)
return web.json_response(
{"success": False, "error": "LoRA not found in cache"}, status=404
)
except Exception as e:
logger.error(f"Error getting lora notes: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
async def get_lora_trigger_words(self, request: web.Request) -> web.Response:
"""Get trigger words for a specific LoRA file"""
try:
lora_name = request.query.get('name')
lora_name = request.query.get("name")
if not lora_name:
return web.Response(text='Lora file name is required', status=400)
return web.Response(text="Lora file name is required", status=400)
trigger_words = await self.service.get_lora_trigger_words(lora_name)
return web.json_response({
'success': True,
'trigger_words': trigger_words
})
return web.json_response({"success": True, "trigger_words": trigger_words})
except Exception as e:
logger.error(f"Error getting lora trigger words: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "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')
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 ''
})
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)
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:
lora_name = request.query.get('name')
lora_name = request.query.get("name")
if not lora_name:
return web.Response(text='Lora file name is required', status=400)
return web.Response(text="Lora file name is required", status=400)
preview_url = await self.service.get_lora_preview_url(lora_name)
if preview_url:
return web.json_response({
'success': True,
'preview_url': preview_url
})
return web.json_response({"success": True, "preview_url": preview_url})
else:
return web.json_response({
'success': False,
'error': 'No preview URL found for the specified lora'
}, status=404)
return web.json_response(
{
"success": False,
"error": "No preview URL found for the specified lora",
},
status=404,
)
except Exception as e:
logger.error(f"Error getting lora preview URL: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
async def get_lora_civitai_url(self, request: web.Request) -> web.Response:
"""Get the Civitai URL for a LoRA file"""
try:
lora_name = request.query.get('name')
lora_name = request.query.get("name")
if not lora_name:
return web.Response(text='Lora file name is required', status=400)
return web.Response(text="Lora file name is required", status=400)
result = await self.service.get_lora_civitai_url(lora_name)
if result['civitai_url']:
return web.json_response({
'success': True,
**result
})
if result["civitai_url"]:
return web.json_response({"success": True, **result})
else:
return web.json_response({
'success': False,
'error': 'No Civitai data found for the specified lora'
}, status=404)
return web.json_response(
{
"success": False,
"error": "No Civitai data found for the specified lora",
},
status=404,
)
except Exception as e:
logger.error(f"Error getting lora Civitai URL: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
async def get_random_loras(self, request: web.Request) -> web.Response:
"""Get random LoRAs based on filters and strength ranges"""
try:
json_data = await request.json()
# Parse parameters
count = json_data.get('count', 5)
count_min = json_data.get('count_min')
count_max = json_data.get('count_max')
model_strength_min = float(json_data.get('model_strength_min', 0.0))
model_strength_max = float(json_data.get('model_strength_max', 1.0))
use_same_clip_strength = json_data.get('use_same_clip_strength', True)
clip_strength_min = float(json_data.get('clip_strength_min', 0.0))
clip_strength_max = float(json_data.get('clip_strength_max', 1.0))
locked_loras = json_data.get('locked_loras', [])
pool_config = json_data.get('pool_config')
count = json_data.get("count", 5)
count_min = json_data.get("count_min")
count_max = json_data.get("count_max")
model_strength_min = float(json_data.get("model_strength_min", 0.0))
model_strength_max = float(json_data.get("model_strength_max", 1.0))
use_same_clip_strength = json_data.get("use_same_clip_strength", True)
clip_strength_min = float(json_data.get("clip_strength_min", 0.0))
clip_strength_max = float(json_data.get("clip_strength_max", 1.0))
locked_loras = json_data.get("locked_loras", [])
pool_config = json_data.get("pool_config")
# Determine target count
if count_min is not None and count_max is not None:
import random
target_count = random.randint(count_min, count_max)
else:
target_count = count
# Validate parameters
if target_count < 1 or target_count > 100:
return web.json_response({
'success': False,
'error': 'Count must be between 1 and 100'
}, status=400)
return web.json_response(
{"success": False, "error": "Count must be between 1 and 100"},
status=400,
)
if model_strength_min < 0 or model_strength_max > 10:
return web.json_response({
'success': False,
'error': 'Model strength must be between 0 and 10'
}, status=400)
if model_strength_min < -10 or model_strength_max > 10:
return web.json_response(
{
"success": False,
"error": "Model strength must be between -10 and 10",
},
status=400,
)
# Get random LoRAs from service
result_loras = await self.service.get_random_loras(
@@ -264,27 +259,19 @@ class LoraRoutes(BaseModelRoutes):
clip_strength_min=clip_strength_min,
clip_strength_max=clip_strength_max,
locked_loras=locked_loras,
pool_config=pool_config
pool_config=pool_config,
)
return web.json_response({
'success': True,
'loras': result_loras,
'count': len(result_loras)
})
return web.json_response(
{"success": True, "loras": result_loras, "count": len(result_loras)}
)
except ValueError as e:
logger.error(f"Invalid parameter for random LoRAs: {e}")
return web.json_response({
'success': False,
'error': str(e)
}, status=400)
return web.json_response({"success": False, "error": str(e)}, status=400)
except Exception as e:
logger.error(f"Error getting random LoRAs: {e}", exc_info=True)
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
async def get_trigger_words(self, request: web.Request) -> web.Response:
"""Get trigger words for specified LoRA models"""
@@ -292,15 +279,17 @@ class LoraRoutes(BaseModelRoutes):
json_data = await request.json()
lora_names = json_data.get("lora_names", [])
node_ids = json_data.get("node_ids", [])
all_trigger_words = []
for lora_name in lora_names:
_, trigger_words = get_lora_info(lora_name)
all_trigger_words.extend(trigger_words)
# Format the trigger words
trigger_words_text = ",, ".join(all_trigger_words) if all_trigger_words else ""
trigger_words_text = (
",, ".join(all_trigger_words) if all_trigger_words else ""
)
# Send update to all connected trigger word toggle nodes
for entry in node_ids:
node_identifier = entry
@@ -314,21 +303,15 @@ class LoraRoutes(BaseModelRoutes):
except (TypeError, ValueError):
parsed_node_id = node_identifier
payload = {
"id": parsed_node_id,
"message": trigger_words_text
}
payload = {"id": parsed_node_id, "message": trigger_words_text}
if graph_identifier is not None:
payload["graph_id"] = str(graph_identifier)
PromptServer.instance.send_sync("trigger_word_update", payload)
return web.json_response({"success": True})
except Exception as e:
logger.error(f"Error getting trigger words: {e}")
return web.json_response({
"success": False,
"error": str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)

View File

@@ -37,155 +37,167 @@ async def test_get_random_loras_success(routes):
"""Test successful random LoRA generation"""
routes.service.random_loras = [
{
'name': 'test_lora_1',
'strength': 0.8,
'clipStrength': 0.8,
'active': True,
'expanded': False,
'locked': False
"name": "test_lora_1",
"strength": 0.8,
"clipStrength": 0.8,
"active": True,
"expanded": False,
"locked": False,
},
{
'name': 'test_lora_2',
'strength': 0.6,
'clipStrength': 0.6,
'active': True,
'expanded': False,
'locked': False
}
"name": "test_lora_2",
"strength": 0.6,
"clipStrength": 0.6,
"active": True,
"expanded": False,
"locked": False,
},
]
request = DummyRequest(json_data={
'count': 5,
'model_strength_min': 0.5,
'model_strength_max': 1.0,
'use_same_clip_strength': True,
'locked_loras': []
})
request = DummyRequest(
json_data={
"count": 5,
"model_strength_min": 0.5,
"model_strength_max": 1.0,
"use_same_clip_strength": True,
"locked_loras": [],
}
)
response = await routes.get_random_loras(request)
payload = json.loads(response.text)
assert response.status == 200
assert payload['success'] is True
assert 'loras' in payload
assert payload['count'] == 2
assert payload["success"] is True
assert "loras" in payload
assert payload["count"] == 2
async def test_get_random_loras_with_range(routes):
"""Test random LoRAs with count range"""
routes.service.random_loras = [
{
'name': 'test_lora_1',
'strength': 0.8,
'clipStrength': 0.8,
'active': True,
'expanded': False,
'locked': False
"name": "test_lora_1",
"strength": 0.8,
"clipStrength": 0.8,
"active": True,
"expanded": False,
"locked": False,
}
]
request = DummyRequest(json_data={
'count_min': 3,
'count_max': 7,
'model_strength_min': 0.0,
'model_strength_max': 1.0,
'use_same_clip_strength': True
})
request = DummyRequest(
json_data={
"count_min": 3,
"count_max": 7,
"model_strength_min": 0.0,
"model_strength_max": 1.0,
"use_same_clip_strength": True,
}
)
response = await routes.get_random_loras(request)
payload = json.loads(response.text)
assert response.status == 200
assert payload['success'] is True
assert payload["success"] is True
async def test_get_random_loras_invalid_count(routes):
"""Test invalid count parameter"""
request = DummyRequest(json_data={
'count': 150, # Over limit
'model_strength_min': 0.0,
'model_strength_max': 1.0
})
request = DummyRequest(
json_data={
"count": 150, # Over limit
"model_strength_min": 0.0,
"model_strength_max": 1.0,
}
)
response = await routes.get_random_loras(request)
payload = json.loads(response.text)
assert response.status == 400
assert payload['success'] is False
assert 'Count must be between 1 and 100' in payload['error']
assert payload["success"] is False
assert "Count must be between 1 and 100" in payload["error"]
async def test_get_random_loras_invalid_strength(routes):
"""Test invalid strength range"""
request = DummyRequest(json_data={
'count': 5,
'model_strength_min': -0.5, # Invalid
'model_strength_max': 1.0
})
request = DummyRequest(
json_data={
"count": 5,
"model_strength_min": -11, # Invalid (below -10)
"model_strength_max": 1.0,
}
)
response = await routes.get_random_loras(request)
payload = json.loads(response.text)
assert response.status == 400
assert payload['success'] is False
assert payload["success"] is False
assert "Model strength must be between -10 and 10" in payload["error"]
async def test_get_random_loras_with_locked(routes):
"""Test random LoRAs with locked items"""
routes.service.random_loras = [
{
'name': 'new_lora',
'strength': 0.7,
'clipStrength': 0.7,
'active': True,
'expanded': False,
'locked': False
"name": "new_lora",
"strength": 0.7,
"clipStrength": 0.7,
"active": True,
"expanded": False,
"locked": False,
},
{
'name': 'locked_lora',
'strength': 0.9,
'clipStrength': 0.9,
'active': True,
'expanded': False,
'locked': True
}
"name": "locked_lora",
"strength": 0.9,
"clipStrength": 0.9,
"active": True,
"expanded": False,
"locked": True,
},
]
request = DummyRequest(json_data={
'count': 5,
'model_strength_min': 0.5,
'model_strength_max': 1.0,
'use_same_clip_strength': True,
'locked_loras': [
{
'name': 'locked_lora',
'strength': 0.9,
'clipStrength': 0.9,
'active': True,
'expanded': False,
'locked': True
}
]
})
request = DummyRequest(
json_data={
"count": 5,
"model_strength_min": 0.5,
"model_strength_max": 1.0,
"use_same_clip_strength": True,
"locked_loras": [
{
"name": "locked_lora",
"strength": 0.9,
"clipStrength": 0.9,
"active": True,
"expanded": False,
"locked": True,
}
],
}
)
response = await routes.get_random_loras(request)
payload = json.loads(response.text)
assert response.status == 200
assert payload['success'] is True
assert payload["success"] is True
async def test_get_random_loras_error(routes, monkeypatch):
"""Test error handling"""
async def failing(*_args, **_kwargs):
raise RuntimeError("Service error")
routes.service.get_random_loras = failing
request = DummyRequest(json_data={'count': 5})
request = DummyRequest(json_data={"count": 5})
response = await routes.get_random_loras(request)
payload = json.loads(response.text)
assert response.status == 500
assert payload['success'] is False
assert 'error' in payload
assert payload["success"] is False
assert "error" in payload

View File

@@ -104,7 +104,7 @@ onMounted(async () => {
// Handle external value updates (e.g., loading workflow, paste)
props.widget.onSetValue = (v) => {
state.restoreFromConfig(v)
state.restoreFromConfig(v as LoraPoolConfig | LegacyLoraPoolConfig)
state.refreshPreview()
}

View File

@@ -7,8 +7,8 @@
<!-- LoRA Count -->
<div class="setting-section">
<label class="setting-label">LoRA Count</label>
<div class="count-mode-selector">
<label class="radio-label">
<div class="count-mode-tabs">
<label class="count-mode-tab" :class="{ active: countMode === 'fixed' }">
<input
type="radio"
name="count-mode"
@@ -16,20 +16,9 @@
:checked="countMode === 'fixed'"
@change="$emit('update:countMode', 'fixed')"
/>
<span>Fixed:</span>
<input
type="number"
class="number-input"
:value="countFixed"
:disabled="countMode !== 'fixed'"
min="1"
max="100"
@input="$emit('update:countFixed', parseInt(($event.target as HTMLInputElement).value))"
/>
<span class="count-mode-tab-label">Fixed</span>
</label>
</div>
<div class="count-mode-selector">
<label class="radio-label">
<label class="count-mode-tab" :class="{ active: countMode === 'range' }">
<input
type="radio"
name="count-mode"
@@ -37,101 +26,82 @@
:checked="countMode === 'range'"
@change="$emit('update:countMode', 'range')"
/>
<span>Range:</span>
<input
type="number"
class="number-input"
:value="countMin"
:disabled="countMode !== 'range'"
min="1"
max="100"
@input="$emit('update:countMin', parseInt(($event.target as HTMLInputElement).value))"
/>
<span>to</span>
<input
type="number"
class="number-input"
:value="countMax"
:disabled="countMode !== 'range'"
min="1"
max="100"
@input="$emit('update:countMax', parseInt(($event.target as HTMLInputElement).value))"
/>
<span class="count-mode-tab-label">Range</span>
</label>
</div>
<div class="slider-container">
<SingleSlider
v-if="countMode === 'fixed'"
:min="1"
:max="10"
:value="countFixed"
:step="1"
:default-range="{ min: 1, max: 5 }"
@update:value="$emit('update:countFixed', $event)"
/>
<DualRangeSlider
v-else
:min="1"
:max="10"
:value-min="countMin"
:value-max="countMax"
:step="1"
:default-range="{ min: 1, max: 5 }"
@update:value-min="$emit('update:countMin', $event)"
@update:value-max="$emit('update:countMax', $event)"
/>
</div>
</div>
<!-- Model Strength Range -->
<div class="setting-section">
<label class="setting-label">Model Strength Range</label>
<div class="strength-inputs">
<div class="strength-input-group">
<label>Min:</label>
<input
type="number"
class="number-input"
:value="modelStrengthMin"
min="0"
max="10"
step="0.1"
@input="$emit('update:modelStrengthMin', parseFloat(($event.target as HTMLInputElement).value))"
/>
</div>
<div class="strength-input-group">
<label>Max:</label>
<input
type="number"
class="number-input"
:value="modelStrengthMax"
min="0"
max="10"
step="0.1"
@input="$emit('update:modelStrengthMax', parseFloat(($event.target as HTMLInputElement).value))"
/>
</div>
<div class="slider-container">
<DualRangeSlider
:min="-10"
:max="10"
:value-min="modelStrengthMin"
:value-max="modelStrengthMax"
:step="0.1"
:default-range="{ min: -2, max: 3 }"
@update:value-min="$emit('update:modelStrengthMin', $event)"
@update:value-max="$emit('update:modelStrengthMax', $event)"
/>
</div>
</div>
<!-- Clip Strength Range -->
<div class="setting-section">
<label class="setting-label">Clip Strength Range</label>
<div class="checkbox-group">
<label class="checkbox-label">
<input
type="checkbox"
:checked="useSameClipStrength"
@change="$emit('update:useSameClipStrength', ($event.target as HTMLInputElement).checked)"
/>
<span>Same as model</span>
<div class="section-header-with-toggle">
<label class="setting-label">
Clip Strength Range - {{ useSameClipStrength ? 'Use Model Strength' : 'Custom Range' }}
</label>
<button
type="button"
class="toggle-switch"
:class="{ 'toggle-switch--active': useSameClipStrength }"
@click="$emit('update:useSameClipStrength', !useSameClipStrength)"
role="switch"
:aria-checked="useSameClipStrength"
title="Lock clip strength to model strength"
>
<span class="toggle-switch__track"></span>
<span class="toggle-switch__thumb"></span>
</button>
</div>
<div class="strength-inputs" :class="{ disabled: isClipStrengthDisabled }">
<div class="strength-input-group">
<label>Min:</label>
<input
type="number"
class="number-input"
:value="clipStrengthMin"
:disabled="isClipStrengthDisabled"
min="0"
max="10"
step="0.1"
@input="$emit('update:clipStrengthMin', parseFloat(($event.target as HTMLInputElement).value))"
/>
</div>
<div class="strength-input-group">
<label>Max:</label>
<input
type="number"
class="number-input"
:value="clipStrengthMax"
:disabled="isClipStrengthDisabled"
min="0"
max="10"
step="0.1"
@input="$emit('update:clipStrengthMax', parseFloat(($event.target as HTMLInputElement).value))"
/>
</div>
<div class="slider-container">
<DualRangeSlider
:min="-10"
:max="10"
:value-min="clipStrengthMin"
:value-max="clipStrengthMax"
:step="0.1"
:default-range="{ min: -1, max: 2 }"
:disabled="isClipStrengthDisabled"
@update:value-min="$emit('update:clipStrengthMin', $event)"
@update:value-max="$emit('update:clipStrengthMax', $event)"
/>
</div>
</div>
@@ -200,6 +170,8 @@
<script setup lang="ts">
import { ref } from 'vue'
import LastUsedPreview from './LastUsedPreview.vue'
import SingleSlider from '../shared/SingleSlider.vue'
import DualRangeSlider from '../shared/DualRangeSlider.vue'
import type { LoraEntry } from '../../composables/types'
defineProps<{
@@ -255,123 +227,155 @@ const areLorasEqual = (a: LoraEntry[] | null, b: LoraEntry[] | null): boolean =>
.randomizer-settings {
display: flex;
flex-direction: column;
gap: 16px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
color: #e4e4e7;
}
.settings-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.settings-title {
font-size: 11px;
font-size: 10px;
font-weight: 600;
letter-spacing: 0.05em;
color: #a1a1aa;
color: var(--fg-color, #fff);
opacity: 0.6;
margin: 0;
text-transform: uppercase;
}
.setting-section {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 16px;
}
.setting-label {
font-size: 12px;
font-weight: 500;
color: #d4d4d8;
display: block;
margin-bottom: 8px;
}
.count-mode-selector,
.roll-mode-selector {
.section-header-with-toggle {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
background: rgba(30, 30, 36, 0.5);
justify-content: space-between;
margin-bottom: 8px;
}
.section-header-with-toggle .setting-label {
margin-bottom: 0;
}
/* Count Mode Tabs */
.count-mode-tabs {
display: flex;
background: rgba(26, 32, 44, 0.9);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 4px;
overflow: hidden;
margin-bottom: 8px;
}
.radio-label {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #e4e4e7;
cursor: pointer;
.count-mode-tab {
flex: 1;
}
.radio-label input[type='radio'] {
position: relative;
padding: 8px 12px;
text-align: center;
cursor: pointer;
transition: all 0.2s ease;
}
.radio-label input[type='radio']:disabled {
cursor: not-allowed;
.count-mode-tab input[type="radio"] {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
.number-input {
width: 60px;
padding: 4px 8px;
background: rgba(20, 20, 24, 0.6);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 3px;
color: #e4e4e7;
font-size: 13px;
}
.number-input:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.strength-inputs {
display: flex;
gap: 12px;
padding: 6px 8px;
background: rgba(30, 30, 36, 0.5);
border-radius: 4px;
}
.strength-inputs.disabled {
opacity: 0.5;
}
.strength-input-group {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
}
.strength-input-group label {
.count-mode-tab-label {
font-size: 12px;
color: #d4d4d8;
font-weight: 500;
color: rgba(226, 232, 240, 0.7);
transition: all 0.2s ease;
}
.checkbox-group {
padding: 6px 8px;
background: rgba(30, 30, 36, 0.5);
.count-mode-tab:hover .count-mode-tab-label {
color: rgba(226, 232, 240, 0.9);
}
.count-mode-tab.active .count-mode-tab-label {
color: rgba(191, 219, 254, 1);
font-weight: 600;
}
.count-mode-tab.active {
background: rgba(66, 153, 225, 0.2);
}
.count-mode-tab.active::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 2px;
background: rgba(66, 153, 225, 0.9);
}
.slider-container {
background: rgba(26, 32, 44, 0.9);
border: 1px solid rgba(226, 232, 240, 0.2);
border-radius: 4px;
padding: 4px 8px;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: #e4e4e7;
/* Toggle Switch (same style as LicenseSection) */
.toggle-switch {
position: relative;
width: 36px;
height: 20px;
padding: 0;
background: transparent;
border: none;
cursor: pointer;
}
.checkbox-label input[type='checkbox'] {
cursor: pointer;
.toggle-switch__track {
position: absolute;
inset: 0;
background: var(--comfy-input-bg, #333);
border: 1px solid var(--border-color, #444);
border-radius: 10px;
transition: all 0.2s;
}
.toggle-switch--active .toggle-switch__track {
background: rgba(66, 153, 225, 0.3);
border-color: rgba(66, 153, 225, 0.6);
}
.toggle-switch__thumb {
position: absolute;
top: 2px;
left: 2px;
width: 14px;
height: 14px;
background: var(--fg-color, #fff);
border-radius: 50%;
transition: all 0.2s;
opacity: 0.6;
}
.toggle-switch--active .toggle-switch__thumb {
transform: translateX(16px);
background: #4299e1;
opacity: 1;
}
.toggle-switch:hover .toggle-switch__thumb {
opacity: 1;
}
/* Roll buttons with tooltip container */

View File

@@ -0,0 +1,295 @@
<template>
<div class="dual-range-slider" :class="{ disabled }" @wheel="onWheel">
<div class="slider-track" ref="trackEl">
<!-- Background track -->
<div class="slider-track__bg"></div>
<!-- Active track (colored range between handles) -->
<div
class="slider-track__active"
:style="{ left: minPercent + '%', width: (maxPercent - minPercent) + '%' }"
></div>
<!-- Default range indicators -->
<div
v-if="defaultRange"
class="slider-track__default"
:style="{
left: defaultMinPercent + '%',
width: (defaultMaxPercent - defaultMinPercent) + '%'
}"
></div>
</div>
<!-- Handles with value labels -->
<div
class="slider-handle slider-handle--min"
:style="{ left: minPercent + '%' }"
@mousedown="startDrag('min', $event)"
@touchstart="startDrag('min', $event)"
>
<div class="slider-handle__thumb"></div>
<div class="slider-handle__value">{{ formatValue(valueMin) }}</div>
</div>
<div
class="slider-handle slider-handle--max"
:style="{ left: maxPercent + '%' }"
@mousedown="startDrag('max', $event)"
@touchstart="startDrag('max', $event)"
>
<div class="slider-handle__thumb"></div>
<div class="slider-handle__value">{{ formatValue(valueMax) }}</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue'
const props = withDefaults(defineProps<{
min: number
max: number
valueMin: number
valueMax: number
step: number
defaultRange?: { min: number; max: number }
disabled?: boolean
}>(), {
disabled: false
})
const emit = defineEmits<{
'update:valueMin': [value: number]
'update:valueMax': [value: number]
}>()
const trackEl = ref<HTMLElement | null>(null)
const dragging = ref<'min' | 'max' | null>(null)
const minPercent = computed(() => {
const range = props.max - props.min
return ((props.valueMin - props.min) / range) * 100
})
const maxPercent = computed(() => {
const range = props.max - props.min
return ((props.valueMax - props.min) / range) * 100
})
const defaultMinPercent = computed(() => {
if (!props.defaultRange) return 0
const range = props.max - props.min
return ((props.defaultRange.min - props.min) / range) * 100
})
const defaultMaxPercent = computed(() => {
if (!props.defaultRange) return 100
const range = props.max - props.min
return ((props.defaultRange.max - props.min) / range) * 100
})
const formatValue = (val: number): string => {
if (Number.isInteger(val)) return val.toString()
return val.toFixed(stepToDecimals(props.step))
}
const stepToDecimals = (step: number): number => {
const str = step.toString()
const decimalIndex = str.indexOf('.')
return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1
}
const snapToStep = (value: number): number => {
const steps = Math.round((value - props.min) / props.step)
return Math.max(props.min, Math.min(props.max, props.min + steps * props.step))
}
const startDrag = (handle: 'min' | 'max', event: MouseEvent | TouchEvent) => {
if (props.disabled) return
event.preventDefault()
dragging.value = handle
document.addEventListener('mousemove', onDrag)
document.addEventListener('mouseup', stopDrag)
document.addEventListener('touchmove', onDrag, { passive: false })
document.addEventListener('touchend', stopDrag)
}
const onDrag = (event: MouseEvent | TouchEvent) => {
if (!trackEl.value || !dragging.value) return
event.preventDefault()
const clientX = 'touches' in event ? event.touches[0].clientX : event.clientX
const rect = trackEl.value.getBoundingClientRect()
const percent = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width))
const rawValue = props.min + percent * (props.max - props.min)
const value = snapToStep(rawValue)
if (dragging.value === 'min') {
const maxAllowed = props.valueMax - props.step
const newValue = Math.min(value, maxAllowed)
emit('update:valueMin', newValue)
} else {
const minAllowed = props.valueMin + props.step
const newValue = Math.max(value, minAllowed)
emit('update:valueMax', newValue)
}
}
const onWheel = (event: WheelEvent) => {
if (props.disabled) return
const rect = trackEl.value?.getBoundingClientRect()
if (!rect) return
const rootRect = (event.currentTarget as HTMLElement).getBoundingClientRect()
if (event.clientX < rootRect.left || event.clientX > rootRect.right ||
event.clientY < rootRect.top || event.clientY > rootRect.bottom) return
event.preventDefault()
const delta = event.deltaY > 0 ? -1 : 1
const relativeX = event.clientX - rect.left
const rangeWidth = rect.width
const minPixel = (minPercent.value / 100) * rangeWidth
const maxPixel = (maxPercent.value / 100) * rangeWidth
if (relativeX < minPixel) {
const newValue = snapToStep(props.valueMin + delta * props.step)
const maxAllowed = props.valueMax - props.step
emit('update:valueMin', Math.min(newValue, maxAllowed))
} else if (relativeX > maxPixel) {
const newValue = snapToStep(props.valueMax + delta * props.step)
const minAllowed = props.valueMin + props.step
emit('update:valueMax', Math.max(newValue, minAllowed))
} else {
const newMin = snapToStep(props.valueMin - delta * props.step)
const newMax = snapToStep(props.valueMax + delta * props.step)
if (newMin < props.valueMin) {
emit('update:valueMin', Math.max(newMin, props.min))
emit('update:valueMax', Math.min(newMax, props.max))
} else {
if (newMin < newMax - props.step) {
emit('update:valueMin', newMin)
emit('update:valueMax', newMax)
}
}
}
}
const stopDrag = () => {
dragging.value = null
document.removeEventListener('mousemove', onDrag)
document.removeEventListener('mouseup', stopDrag)
document.removeEventListener('touchmove', onDrag)
document.removeEventListener('touchend', stopDrag)
}
onUnmounted(() => {
stopDrag()
})
</script>
<style scoped>
.dual-range-slider {
position: relative;
width: 100%;
height: 32px;
user-select: none;
}
.dual-range-slider.disabled {
opacity: 0.4;
pointer-events: none;
}
.slider-track {
position: absolute;
top: 14px;
left: 0;
right: 0;
height: 4px;
background: var(--comfy-input-bg, #333);
border-radius: 2px;
}
.slider-track__bg {
position: absolute;
inset: 0;
background: rgba(66, 153, 225, 0.15);
border-radius: 2px;
}
.slider-track__active {
position: absolute;
top: 0;
bottom: 0;
background: rgba(66, 153, 225, 0.6);
border-radius: 2px;
transition: left 0.05s linear, width 0.05s linear;
}
.slider-track__default {
position: absolute;
top: 0;
bottom: 0;
background: rgba(66, 153, 225, 0.1);
border-radius: 2px;
}
.slider-handle {
position: absolute;
top: 0;
transform: translateX(-50%);
cursor: grab;
z-index: 2;
}
.slider-handle:active {
cursor: grabbing;
}
.slider-handle__thumb {
width: 12px;
height: 12px;
background: var(--fg-color, #fff);
border-radius: 50%;
position: absolute;
top: 10px;
left: 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
transition: transform 0.15s ease;
}
.slider-handle:hover .slider-handle__thumb {
transform: scale(1.1);
}
.slider-handle:active .slider-handle__thumb {
transform: scale(1.15);
}
.slider-handle__value {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
font-size: 10px;
font-family: 'SF Mono', 'Roboto Mono', monospace;
color: var(--fg-color, #fff);
opacity: 0.8;
white-space: nowrap;
pointer-events: none;
}
.slider-handle--min .slider-handle__value {
text-align: center;
}
.slider-handle--max .slider-handle__value {
text-align: center;
}
</style>

View File

@@ -0,0 +1,235 @@
<template>
<div class="single-slider" :class="{ disabled }" @wheel="onWheel">
<div class="slider-track" ref="trackEl">
<div class="slider-track__bg"></div>
<div
class="slider-track__active"
:style="{ width: percent + '%' }"
></div>
<div
v-if="defaultRange"
class="slider-track__default"
:style="{
left: defaultMinPercent + '%',
width: (defaultMaxPercent - defaultMinPercent) + '%'
}"
></div>
</div>
<div
class="slider-handle"
:style="{ left: percent + '%' }"
@mousedown="startDrag($event)"
@touchstart="startDrag($event)"
>
<div class="slider-handle__thumb"></div>
<div class="slider-handle__value">{{ formatValue(value) }}</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue'
const props = withDefaults(defineProps<{
min: number
max: number
value: number
step: number
defaultRange?: { min: number; max: number }
disabled?: boolean
}>(), {
disabled: false
})
const emit = defineEmits<{
'update:value': [value: number]
}>()
const trackEl = ref<HTMLElement | null>(null)
const dragging = ref(false)
const percent = computed(() => {
const range = props.max - props.min
return ((props.value - props.min) / range) * 100
})
const defaultMinPercent = computed(() => {
if (!props.defaultRange) return 0
const range = props.max - props.min
return ((props.defaultRange.min - props.min) / range) * 100
})
const defaultMaxPercent = computed(() => {
if (!props.defaultRange) return 100
const range = props.max - props.min
return ((props.defaultRange.max - props.min) / range) * 100
})
const formatValue = (val: number): string => {
if (Number.isInteger(val)) return val.toString()
return val.toFixed(stepToDecimals(props.step))
}
const stepToDecimals = (step: number): number => {
const str = step.toString()
const decimalIndex = str.indexOf('.')
return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1
}
const snapToStep = (value: number): number => {
const steps = Math.round((value - props.min) / props.step)
return Math.max(props.min, Math.min(props.max, props.min + steps * props.step))
}
const startDrag = (event: MouseEvent | TouchEvent) => {
if (props.disabled) return
event.preventDefault()
dragging.value = true
document.addEventListener('mousemove', onDrag)
document.addEventListener('mouseup', stopDrag)
document.addEventListener('touchmove', onDrag, { passive: false })
document.addEventListener('touchend', stopDrag)
onDrag(event)
}
const onDrag = (event: MouseEvent | TouchEvent) => {
if (!trackEl.value || !dragging.value) return
event.preventDefault()
const clientX = 'touches' in event ? event.touches[0].clientX : event.clientX
const rect = trackEl.value.getBoundingClientRect()
const percent = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width))
const rawValue = props.min + percent * (props.max - props.min)
const value = snapToStep(rawValue)
emit('update:value', value)
}
const onWheel = (event: WheelEvent) => {
if (props.disabled) return
const rect = trackEl.value?.getBoundingClientRect()
if (!rect) return
const rootRect = (event.currentTarget as HTMLElement).getBoundingClientRect()
if (event.clientX < rootRect.left || event.clientX > rootRect.right ||
event.clientY < rootRect.top || event.clientY > rootRect.bottom) return
event.preventDefault()
const delta = event.deltaY > 0 ? -1 : 1
const newValue = snapToStep(props.value + delta * props.step)
emit('update:value', newValue)
}
const stopDrag = () => {
dragging.value = false
document.removeEventListener('mousemove', onDrag)
document.removeEventListener('mouseup', stopDrag)
document.removeEventListener('touchmove', onDrag)
document.removeEventListener('touchend', stopDrag)
}
onUnmounted(() => {
stopDrag()
})
</script>
<style scoped>
.single-slider {
position: relative;
width: 100%;
height: 32px;
user-select: none;
}
.single-slider.disabled {
opacity: 0.4;
pointer-events: none;
}
.slider-track {
position: absolute;
top: 14px;
left: 0;
right: 0;
height: 4px;
background: var(--comfy-input-bg, #333);
border-radius: 2px;
}
.slider-track__bg {
position: absolute;
inset: 0;
background: rgba(66, 153, 225, 0.15);
border-radius: 2px;
}
.slider-track__active {
position: absolute;
top: 0;
bottom: 0;
left: 0;
background: rgba(66, 153, 225, 0.6);
border-radius: 2px;
transition: width 0.05s linear;
}
.slider-track__default {
position: absolute;
top: 0;
bottom: 0;
background: rgba(66, 153, 225, 0.1);
border-radius: 2px;
}
.slider-handle {
position: absolute;
top: 0;
transform: translateX(-50%);
cursor: grab;
z-index: 2;
}
.slider-handle:active {
cursor: grabbing;
}
.slider-handle__thumb {
width: 12px;
height: 12px;
background: var(--fg-color, #fff);
border-radius: 50%;
position: absolute;
top: 10px;
left: 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
transition: transform 0.15s ease;
}
.slider-handle:hover .slider-handle__thumb {
transform: scale(1.1);
}
.slider-handle:active .slider-handle__thumb {
transform: scale(1.15);
}
.slider-handle__value {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
font-size: 10px;
font-family: 'SF Mono', 'Roboto Mono', monospace;
color: var(--fg-color, #fff);
opacity: 0.8;
white-space: nowrap;
pointer-events: none;
}
</style>

View File

@@ -7,8 +7,8 @@ import type { LoraPoolConfig, LegacyLoraPoolConfig, RandomizerConfig } from './c
const LORA_POOL_WIDGET_MIN_WIDTH = 500
const LORA_POOL_WIDGET_MIN_HEIGHT = 400
const LORA_RANDOMIZER_WIDGET_MIN_WIDTH = 500
const LORA_RANDOMIZER_WIDGET_MIN_HEIGHT = 462
const LORA_RANDOMIZER_WIDGET_MAX_HEIGHT = 462
const LORA_RANDOMIZER_WIDGET_MIN_HEIGHT = 430
const LORA_RANDOMIZER_WIDGET_MAX_HEIGHT = LORA_RANDOMIZER_WIDGET_MIN_HEIGHT
// @ts-ignore - ComfyUI external module
import { app } from '../../../scripts/app.js'
@@ -231,7 +231,7 @@ app.registerExtension({
const isRandomizerNode = node.comfyClass === 'Lora Randomizer (LoraManager)'
// For randomizer nodes, add a callback to update connected trigger words
const callback = isRandomizerNode ? (value: any) => {
const callback = isRandomizerNode ? () => {
updateDownstreamLoaders(node)
} : null

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long