HEL-892: pin AudioCrop and GuHai split reference contracts
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -25,6 +25,7 @@ from calliope.comfyui.serialization_reference import (
|
||||
ASR_PROFILE,
|
||||
AUX_PROFILE,
|
||||
CASE04_PROFILE,
|
||||
CROP_SPLIT_PROFILES,
|
||||
MEDIA_PROFILES,
|
||||
MP3_PROFILE,
|
||||
PREVIEW_PROFILE,
|
||||
@@ -289,6 +290,7 @@ REFERENCE_PROFILES = (
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
*CROP_SPLIT_PROFILES,
|
||||
)
|
||||
|
||||
|
||||
@@ -305,7 +307,7 @@ def canonical_sha(value):
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def node_inventory(source):
|
||||
def node_inventory(source, *, include_aux=False):
|
||||
rows = []
|
||||
graphs = [("", source)] + [
|
||||
(f"/definitions/subgraphs/{i}", graph)
|
||||
@@ -319,7 +321,8 @@ def node_inventory(source):
|
||||
"pointer": f"{prefix}/nodes/{i}",
|
||||
"node_id": str(node.get("id")),
|
||||
"type": node.get("type"),
|
||||
"provider": props.get("cnr_id"),
|
||||
"provider": props.get("cnr_id")
|
||||
or (props.get("aux_id") if include_aux else None),
|
||||
"version": props.get("ver"),
|
||||
"mode": node.get("mode", 0),
|
||||
"widget_count": len(node.get("widgets_values", [])),
|
||||
@@ -380,6 +383,16 @@ def media_field_evidence(source, prompt, profile):
|
||||
"SaveAudioMP3": ("filename_prefix", "quality"),
|
||||
"PreviewAudio": (),
|
||||
"AudioSeparation": ("chunk_fade_shape", "chunk_length", "chunk_overlap"),
|
||||
"AudioCrop": ("start_time", "end_time"),
|
||||
"GuHaiAutoImageSplit": (
|
||||
"保存目录",
|
||||
"水平张数",
|
||||
"垂直张数",
|
||||
"移除画布边缘",
|
||||
"移除描边",
|
||||
"文件名前缀",
|
||||
"保存格式",
|
||||
),
|
||||
"LoadImage": ("image",),
|
||||
"PreviewImage": (),
|
||||
"LayerUtility: ImageReel": (
|
||||
@@ -432,7 +445,9 @@ def media_field_evidence(source, prompt, profile):
|
||||
"source_pointer": pointer,
|
||||
"rule": rule,
|
||||
"profile": profile,
|
||||
"contract_manifest": "separation-reference/contract.json"
|
||||
"contract_manifest": "crop-split-reference/contract.json"
|
||||
if profile in CROP_SPLIT_PROFILES
|
||||
else "separation-reference/contract.json"
|
||||
if profile == SEPARATION_PROFILE
|
||||
else "media-reference/contract.json",
|
||||
}
|
||||
@@ -494,26 +509,55 @@ def profile_attempt(source, profile):
|
||||
"separation-reference/sources.json",
|
||||
*assumptions["reference_sources"],
|
||||
]
|
||||
if profile in CROP_SPLIT_PROFILES:
|
||||
assumptions["crop_split_reference"] = {
|
||||
"selected_profile": profile,
|
||||
"node_contracts": "crop-split-reference/contract.json",
|
||||
"unmodified_plugin_and_frontend": True,
|
||||
"target_node_version_and_UE_match": "unknown",
|
||||
"registry_commit_binding": "unknown",
|
||||
}
|
||||
assumptions["reference_sources"] = [
|
||||
"crop-split-reference/sources.json",
|
||||
"separation-reference/sources.json",
|
||||
*assumptions["reference_sources"],
|
||||
]
|
||||
base = {"profile": profile, "assumptions": assumptions}
|
||||
if profile in CROP_SPLIT_PROFILES:
|
||||
base["source_declarations"] = [
|
||||
{
|
||||
"pointer": f"/nodes/{i}",
|
||||
**{k: (n.get("properties") or {}).get(k) for k in ("cnr_id", "aux_id", "ver")},
|
||||
}
|
||||
for i, n in enumerate(source.get("nodes", []))
|
||||
]
|
||||
base["verified_reference_facts"] = "crop-split-reference/verified-facts.json"
|
||||
declared_frontend = (source.get("extra") or {}).get("frontendVersion")
|
||||
assumptions["source_frontend_declaration"] = declared_frontend
|
||||
assumptions["missing_frontend_policy"] = (
|
||||
"explicit_media_reference_assumption"
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE)
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES)
|
||||
else "explicit_legacy_reference_assumption"
|
||||
if profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE)
|
||||
else "requires_explicit_declaration"
|
||||
)
|
||||
assumptions["missing_node_declarations"] = [
|
||||
n["pointer"]
|
||||
for n in node_inventory(source)
|
||||
for n in node_inventory(source, include_aux=profile in CROP_SPLIT_PROFILES)
|
||||
if n["type"] not in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode")
|
||||
and (n["provider"] is None or n["version"] is None)
|
||||
]
|
||||
if declared_frontend != expected and not (
|
||||
declared_frontend is None
|
||||
and profile
|
||||
in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, *MEDIA_PROFILES, SEPARATION_PROFILE)
|
||||
in (
|
||||
PROFILE,
|
||||
AUX_PROFILE,
|
||||
PRIMITIVE_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
*CROP_SPLIT_PROFILES,
|
||||
)
|
||||
):
|
||||
return {
|
||||
**base,
|
||||
@@ -550,7 +594,7 @@ def profile_attempt(source, profile):
|
||||
{"field_evidence": asr_field_evidence(source, result.prompt)}
|
||||
if profile == ASR_PROFILE
|
||||
else {"field_evidence": media_field_evidence(source, result.prompt, profile)}
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE)
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES)
|
||||
else {}
|
||||
),
|
||||
}
|
||||
@@ -627,7 +671,12 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
|
||||
if attempt["status"] != "rejected":
|
||||
continue
|
||||
for issue in attempt["issues"]:
|
||||
matches = [n for n in inventory if n["node_id"] == issue.get("node_id")]
|
||||
gap_inventory = (
|
||||
node_inventory(source, include_aux=True)
|
||||
if attempt["profile"] in CROP_SPLIT_PROFILES
|
||||
else inventory
|
||||
)
|
||||
matches = [n for n in gap_inventory if n["node_id"] == issue.get("node_id")]
|
||||
for node in matches or [{}]:
|
||||
key = (
|
||||
node.get("type"),
|
||||
@@ -649,7 +698,7 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
|
||||
for cohort in ("without_companion", "with_companion")
|
||||
}
|
||||
if baseline_profiles is None:
|
||||
baseline_profiles = tuple(p for p in profiles if p != SEPARATION_PROFILE)
|
||||
baseline_profiles = tuple(p for p in profiles if p not in CROP_SPLIT_PROFILES)
|
||||
old_complete = {
|
||||
row["source_path"]
|
||||
for row in rows
|
||||
@@ -704,6 +753,7 @@ def main():
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
*CROP_SPLIT_PROFILES,
|
||||
PROFILE,
|
||||
AUX_PROFILE,
|
||||
PRIMITIVE_PROFILE,
|
||||
|
||||
@@ -18,6 +18,10 @@ REEL_PROFILE = "comfy-frontend-1.37.11-layerstyle-mixed-core-0.4.0-reference"
|
||||
MEDIA_PROFILES = (MP3_PROFILE, REEL_PROFILE)
|
||||
SEPARATION_PROFILE = "comfy-frontend-1.37.11-audio-separation-1.4.0-core-mixed-reference"
|
||||
|
||||
CROP_PROFILE = "comfy-frontend-1.37.11-audio-crop-1.4.0-core-0.3.68-reference"
|
||||
SPLIT_PROFILE = "comfy-frontend-1.37.11-guhai-885cac3d-core-0.21.1-reference"
|
||||
CROP_SPLIT_PROFILES = (CROP_PROFILE, SPLIT_PROFILE)
|
||||
|
||||
ASR_PROFILE = "comfy-frontend-1.37.11-asr-b037d7be-reference"
|
||||
PROFILE = "comfy-frontend-1.37.11-core-reference"
|
||||
AUX_PROFILE = "comfy-frontend-1.37.11-controlnet-aux-e8b689a-reference"
|
||||
@@ -88,7 +92,7 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE):
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
|
||||
return media_definitions(profile)
|
||||
if profile == ASR_PROFILE:
|
||||
definitions = reference_definitions(PREVIEW_PROFILE)
|
||||
@@ -162,7 +166,7 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
|
||||
|
||||
def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]:
|
||||
"""Apply only the pinned identity serializers; reject any extra/missing value."""
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE):
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
|
||||
return serialize_media_node(node, profile)
|
||||
if profile == ASR_PROFILE:
|
||||
if any(k in node for k in ("widgets", "widgets_values_named", "serializeValue")):
|
||||
@@ -1039,6 +1043,16 @@ _MEDIA_LAYOUTS = {
|
||||
"LoadAudio": (("audio", str),),
|
||||
"SaveAudioMP3": (("filename_prefix", str), ("quality", str)),
|
||||
"PreviewAudio": (),
|
||||
"AudioCrop": (("start_time", str), ("end_time", str)),
|
||||
"GuHaiAutoImageSplit": (
|
||||
("保存目录", str),
|
||||
("水平张数", int),
|
||||
("垂直张数", int),
|
||||
("移除画布边缘", bool),
|
||||
("移除描边", int),
|
||||
("文件名前缀", str),
|
||||
("保存格式", str),
|
||||
),
|
||||
"AudioSeparation": (
|
||||
("chunk_fade_shape", str),
|
||||
("chunk_length", float),
|
||||
@@ -1073,6 +1087,32 @@ def media_definitions(profile):
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
if profile == SPLIT_PROFILE:
|
||||
definitions = reference_definitions(PROFILE)
|
||||
return {
|
||||
"LoadImage": definitions["LoadImage"],
|
||||
"PreviewImage": definitions["PreviewImage"],
|
||||
"GuHaiAutoImageSplit": spec(
|
||||
{
|
||||
"图像": "IMAGE",
|
||||
"保存目录": "STRING",
|
||||
"水平张数": "INT",
|
||||
"垂直张数": "INT",
|
||||
"移除画布边缘": "BOOLEAN",
|
||||
"移除描边": "INT",
|
||||
"文件名前缀": "STRING",
|
||||
"保存格式": "COMBO",
|
||||
},
|
||||
["IMAGE"],
|
||||
),
|
||||
}
|
||||
if profile == CROP_PROFILE:
|
||||
definitions = media_definitions(SEPARATION_PROFILE)
|
||||
del definitions["SaveAudioMP3"]
|
||||
definitions["AudioCrop"] = spec(
|
||||
{"audio": "AUDIO", "start_time": "STRING", "end_time": "STRING"}, ["AUDIO"]
|
||||
)
|
||||
return definitions
|
||||
if profile == SEPARATION_PROFILE:
|
||||
definitions = media_definitions(MP3_PROFILE)
|
||||
definitions["PreviewAudio"] = spec({"audio": "AUDIO"}, [], {"audioUI": "AUDIO_UI"})
|
||||
@@ -1132,7 +1172,7 @@ def serialize_media_node(node, profile):
|
||||
raise ValueError("节点类型/模式不在媒体固定参考契约内")
|
||||
if any(k in node for k in ("widgets", "widgets_values_named", "serializeValue")):
|
||||
raise ValueError("媒体参考不支持自定义控件/serializer覆盖")
|
||||
if profile == SEPARATION_PROFILE:
|
||||
if profile in (SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
|
||||
if type(node.get("mode", 0)) is not int:
|
||||
raise ValueError("音频分离参考模式必须为整数0")
|
||||
ue = props.get("ue_properties") or {}
|
||||
@@ -1145,9 +1185,21 @@ def serialize_media_node(node, profile):
|
||||
type(output["slot_index"]) is not int or output["slot_index"] != slot
|
||||
):
|
||||
raise ValueError("音频分离输出槽索引冲突")
|
||||
if profile in CROP_SPLIT_PROFILES:
|
||||
output_names = {
|
||||
"AudioCrop": ["AUDIO"],
|
||||
"LoadAudio": ["AUDIO"],
|
||||
"PreviewAudio": [],
|
||||
"AudioSeparation": ["Bass", "Drums", "Other", "Vocals"],
|
||||
"LoadImage": ["IMAGE", "MASK"],
|
||||
"PreviewImage": [],
|
||||
"GuHaiAutoImageSplit": ["分割图像"],
|
||||
}[ct]
|
||||
if [s.get("name") for s in node.get("outputs", [])] != output_names:
|
||||
raise ValueError("源输出槽/名称与固定参考契约不符")
|
||||
provider = (
|
||||
"audio-separation-nodes-comfyui"
|
||||
if ct == "AudioSeparation"
|
||||
if ct in ("AudioSeparation", "AudioCrop")
|
||||
else ("comfyui_layerstyle" if ct.startswith("LayerUtility:") else "comfy-core")
|
||||
)
|
||||
version = (
|
||||
@@ -1156,8 +1208,13 @@ def serialize_media_node(node, profile):
|
||||
"PreviewAudio": "0.3.68",
|
||||
"SaveAudioMP3": "0.3.71",
|
||||
"AudioSeparation": "1.4.0",
|
||||
"AudioCrop": "1.4.0",
|
||||
}[ct]
|
||||
if profile == SEPARATION_PROFILE
|
||||
if profile in (SEPARATION_PROFILE, CROP_PROFILE)
|
||||
else "885cac3dd323d26a77b69ae904a9a344f0dee7d0"
|
||||
if ct == "GuHaiAutoImageSplit"
|
||||
else "0.21.1"
|
||||
if profile == SPLIT_PROFILE
|
||||
else _REEL_VERSION
|
||||
if ct == "LayerUtility: ImageReel"
|
||||
else _COMPOSIT_VERSION
|
||||
@@ -1166,10 +1223,18 @@ def serialize_media_node(node, profile):
|
||||
if profile == MP3_PROFILE
|
||||
else "0.4.0"
|
||||
)
|
||||
if ct == "GuHaiAutoImageSplit":
|
||||
if props.get("aux_id") != "goohai/Goohaitools-comfyui" or props.get("cnr_id") is not None:
|
||||
raise ValueError("GuHai要求精确aux_id且无未经证明的cnr_id")
|
||||
provider_key, provider = "aux_id", "goohai/Goohaitools-comfyui"
|
||||
else:
|
||||
provider_key = "cnr_id"
|
||||
if profile in CROP_SPLIT_PROFILES and props.get("aux_id") is not None:
|
||||
raise ValueError("参考节点含未证明的额外提供方声明")
|
||||
# Audio has neither declaration; allow absence only in this labeled profile.
|
||||
if any(
|
||||
props.get(k) != v and not (profile == MP3_PROFILE and props.get(k) is None)
|
||||
for k, v in (("cnr_id", provider), ("ver", version))
|
||||
for k, v in ((provider_key, provider), ("ver", version))
|
||||
):
|
||||
raise ValueError("媒体节点提供方/版本与固定参考冲突")
|
||||
layout = _MEDIA_LAYOUTS[ct]
|
||||
@@ -1202,6 +1267,14 @@ def serialize_media_node(node, profile):
|
||||
"exponential",
|
||||
):
|
||||
raise ValueError("AudioSeparation chunk_fade_shape静态枚举不符")
|
||||
if ct == "GuHaiAutoImageSplit":
|
||||
# The plugin declares only minimums. 2048 is the pinned frontend's
|
||||
# default UI maximum, not a plugin/server bound. Never clamp/round.
|
||||
for name, low in (("水平张数", 1), ("垂直张数", 1), ("移除描边", 0)):
|
||||
if not low <= result[name] <= 2048:
|
||||
raise ValueError(f"{name}超出固定参考UI边界")
|
||||
if result["保存格式"] not in ("PNG", "JPG"):
|
||||
raise ValueError("GuHai保存格式静态枚举不符")
|
||||
if ct == "SaveAudioMP3" and result["quality"] not in ("V0", "128k", "320k"):
|
||||
raise ValueError("MP3 quality静态枚举不符")
|
||||
if ct == "LayerUtility: ImageReelComposit" and result["color_theme"] not in ("light", "dark"):
|
||||
@@ -1227,7 +1300,9 @@ def serialize_media_node(node, profile):
|
||||
sockets = node.get("inputs", [])
|
||||
if len(sockets) != len(slots) or {s.get("name") for s in sockets} != set(slots):
|
||||
raise ValueError("媒体输入槽缺失/重复/额外")
|
||||
if profile == SEPARATION_PROFILE and [s.get("name") for s in sockets] != list(slots):
|
||||
if profile in (SEPARATION_PROFILE, *CROP_SPLIT_PROFILES) and [
|
||||
s.get("name") for s in sockets
|
||||
] != list(slots):
|
||||
raise ValueError("音频分离参考输入/控件构造顺序不符")
|
||||
for socket in sockets:
|
||||
name = socket["name"]
|
||||
|
||||
@@ -17,6 +17,7 @@ from .serialization_reference import (
|
||||
ASR_PROFILE,
|
||||
AUX_PROFILE,
|
||||
CASE04_PROFILE,
|
||||
CROP_SPLIT_PROFILES,
|
||||
MEDIA_PROFILES,
|
||||
PREVIEW_PROFILE,
|
||||
PRIMITIVE_PROFILE,
|
||||
@@ -63,6 +64,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
*CROP_SPLIT_PROFILES,
|
||||
AUX_PROFILE,
|
||||
PRIMITIVE_PROFILE,
|
||||
PREVIEW_PROFILE,
|
||||
@@ -126,11 +128,11 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
and (source.get("extra") or {}).get("frontendVersion") != "1.37.11"
|
||||
):
|
||||
raise ValueError("PreviewAny 需要显式1.37.11前端声明")
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE) and any(
|
||||
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES) and any(
|
||||
node.get("type") == "Reroute" for node in source.get("nodes", [])
|
||||
):
|
||||
raise ValueError("媒体最小参考仅覆盖直接连线,不扩展虚拟节点")
|
||||
if profile == SEPARATION_PROFILE and any(
|
||||
if profile in (SEPARATION_PROFILE, *CROP_SPLIT_PROFILES) and any(
|
||||
(source.get("extra") or {}).get(k) for k in ("ue_links", "links_added_by_ue")
|
||||
):
|
||||
raise ValueError("音频分离参考不覆盖UE附加连线")
|
||||
@@ -145,7 +147,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc:
|
||||
return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True)
|
||||
result.reference_only = True
|
||||
if profile in (ASR_PROFILE, *MEDIA_PROFILES, SEPARATION_PROFILE):
|
||||
if profile in (ASR_PROFILE, *MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
|
||||
result.serialization_stage = "restored_saved_state_before_queue_hooks"
|
||||
return result
|
||||
|
||||
@@ -226,7 +228,7 @@ def _convert(
|
||||
for lid in links:
|
||||
try:
|
||||
resolve_reference_link(nodes, links, lid)
|
||||
if reference_profile in (*MEDIA_PROFILES, SEPARATION_PROFILE):
|
||||
if reference_profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
|
||||
link = links[lid]
|
||||
upstream = nodes[str(link[1])]["outputs"][link[2]]
|
||||
downstream = nodes[str(link[3])]["inputs"][link[4]]
|
||||
@@ -284,6 +286,7 @@ def _convert(
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
*CROP_SPLIT_PROFILES,
|
||||
)
|
||||
and ct == "LoadAudio"
|
||||
):
|
||||
|
||||
@@ -359,9 +359,10 @@ def test_old_mp3_profile_rejects_real_graph_and_new_profile_rejects_old_core():
|
||||
|
||||
def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_comparisons():
|
||||
previous = json.loads((REPO / "docs/hel-892/media-evidence/library.json").read_bytes())
|
||||
baseline = tuple(p for p in audit.REFERENCE_PROFILES if p != SEPARATION_PROFILE)
|
||||
profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in audit.CROP_SPLIT_PROFILES)
|
||||
baseline = tuple(p for p in profiles if p != SEPARATION_PROFILE)
|
||||
old = audit.audit_library(REPO, baseline)
|
||||
current = audit.audit_library(REPO)
|
||||
current = audit.audit_library(REPO, profiles, baseline_profiles=baseline)
|
||||
for historical, before, after in zip(previous["cases"], old["cases"], current["cases"]):
|
||||
assert historical["source_path"] == before["source_path"] == after["source_path"]
|
||||
assert historical["attempts"] == before["attempts"] == after["attempts"][:-1]
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
"""Read pinned source AST/bytes; synthetic mutations never execute upstream plugins."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from scripts import audit_reference_conversion as audit
|
||||
|
||||
from calliope.comfyui.serialization_reference import (
|
||||
CROP_PROFILE,
|
||||
CROP_SPLIT_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
SPLIT_PROFILE,
|
||||
serialize_reference_widgets,
|
||||
)
|
||||
from calliope.comfyui.ui2api import convert, convert_reference
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
SOURCES = REPO / "docs/hel-892/crop-split-reference"
|
||||
PREFIX = "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/"
|
||||
CROP = PREFIX + "音频人声分离.json"
|
||||
SPLIT = PREFIX + "图像分割-多宫格分割.json"
|
||||
LAYOUTS = {
|
||||
"AudioCrop": ["start_time", "end_time"],
|
||||
"GuHaiAutoImageSplit": [
|
||||
"保存目录",
|
||||
"水平张数",
|
||||
"垂直张数",
|
||||
"移除画布边缘",
|
||||
"移除描边",
|
||||
"文件名前缀",
|
||||
"保存格式",
|
||||
],
|
||||
"AudioSeparation": ["chunk_fade_shape", "chunk_length", "chunk_overlap"],
|
||||
"LoadAudio": ["audio"],
|
||||
"PreviewAudio": [],
|
||||
"LoadImage": ["image"],
|
||||
"PreviewImage": [],
|
||||
}
|
||||
|
||||
|
||||
def graph(profile):
|
||||
return json.loads((REPO / (CROP if profile == CROP_PROFILE else SPLIT)).read_bytes())
|
||||
|
||||
|
||||
def node(source, nid):
|
||||
return next(n for n in source["nodes"] if n["id"] == nid)
|
||||
|
||||
|
||||
def synthetic_split():
|
||||
# ONLY this synthetic fixture removes the unexplained source PreviewImage
|
||||
# output. The original remains unchanged/rejected in all library audits.
|
||||
source = graph(SPLIT_PROFILE)
|
||||
node(source, 3)["outputs"] = []
|
||||
return source
|
||||
|
||||
|
||||
def schema_and_class(filename, name):
|
||||
tree = ast.parse((SOURCES / filename).read_bytes())
|
||||
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name)
|
||||
method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "INPUT_TYPES")
|
||||
schema = ast.literal_eval(next(n.value for n in ast.walk(method) if isinstance(n, ast.Return)))
|
||||
return tree, cls, schema
|
||||
|
||||
|
||||
def test_pinned_ast_schemas_and_registration_no_plugin_import():
|
||||
_, crop, schema = schema_and_class("crop.py", "AudioCrop")
|
||||
assert list(schema["required"]) == ["audio", "start_time", "end_time"]
|
||||
assert schema["required"]["start_time"] == ("STRING", {"default": "0:00"})
|
||||
assert schema["required"]["end_time"] == ("STRING", {"default": "1:00"})
|
||||
tree, split, schema = schema_and_class("guhai__nodes__自动分割图像.py", "GuHaiAutoImageSplit")
|
||||
assert list(schema["required"]) == ["图像", *LAYOUTS["GuHaiAutoImageSplit"]]
|
||||
assert schema["required"]["水平张数"] == ("INT", {"default": 4, "min": 1})
|
||||
assert schema["required"]["垂直张数"] == ("INT", {"default": 2, "min": 1})
|
||||
assert schema["required"]["移除描边"] == ("INT", {"default": 0, "min": 0})
|
||||
assert schema["required"]["保存格式"] == (["PNG", "JPG"], {"default": "PNG"})
|
||||
mapping = next(
|
||||
n.value
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == "NODE_CLASS_MAPPINGS" for t in n.targets)
|
||||
)
|
||||
assert [(k.value, v.id) for k, v in zip(mapping.keys, mapping.values)] == [
|
||||
("GuHaiAutoImageSplit", "GuHaiAutoImageSplit")
|
||||
]
|
||||
for cls in (crop, split):
|
||||
returns = next(
|
||||
n.value
|
||||
for n in cls.body
|
||||
if isinstance(n, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == "RETURN_TYPES" for t in n.targets)
|
||||
)
|
||||
assert ast.literal_eval(returns) == (("AUDIO",) if cls is crop else ("IMAGE",))
|
||||
|
||||
|
||||
def independently_check(source, attempt):
|
||||
prompt = attempt["candidate_prompt"]
|
||||
assert set(prompt) == {str(n["id"]) for n in source["nodes"]}
|
||||
for n in source["nodes"]:
|
||||
actual = prompt[str(n["id"])]
|
||||
expected = dict(zip(LAYOUTS[n["type"]], n["widgets_values"]))
|
||||
if n["type"] in ("LoadAudio", "PreviewAudio"):
|
||||
expected["audioUI"] = ""
|
||||
for socket in n["inputs"]:
|
||||
if socket["link"] is not None:
|
||||
link = next(link for link in source["links"] if link[0] == socket["link"])
|
||||
expected[socket["name"]] = [str(link[1]), link[2]]
|
||||
assert actual == {
|
||||
"class_type": n["type"],
|
||||
"inputs": expected,
|
||||
"_meta": {"title": n.get("title") or n["type"]},
|
||||
}
|
||||
assert {k: type(v) for k, v in expected.items()} == {
|
||||
k: type(v) for k, v in actual["inputs"].items()
|
||||
}
|
||||
for field in attempt["field_evidence"]:
|
||||
pointer = field["source_pointer"]
|
||||
if pointer is None:
|
||||
assert field["field"] == "audioUI" and field["value"] == ""
|
||||
continue
|
||||
value = source
|
||||
for part in pointer.split("/")[1:]:
|
||||
value = value[int(part)] if isinstance(value, list) else value[part]
|
||||
if pointer.startswith("/links/"):
|
||||
value = [str(value[1]), value[2]]
|
||||
assert type(value) is type(field["value"]) and value == field["value"]
|
||||
raw = json.dumps(
|
||||
prompt, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False
|
||||
).encode()
|
||||
assert attempt["candidate_sha256"] == hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def test_actual_crop_candidate_every_field_type_pointer_and_final_nonzero_slot():
|
||||
source = graph(CROP_PROFILE)
|
||||
original = copy.deepcopy(source)
|
||||
attempt = audit.profile_attempt(source, CROP_PROFILE)
|
||||
assert attempt["status"] == "complete_reference_candidate"
|
||||
independently_check(source, attempt)
|
||||
assert len(attempt["field_evidence"]) == 11
|
||||
assert attempt["candidate_prompt"]["11"]["inputs"]["audio"] == ["18", 0]
|
||||
assert attempt["candidate_prompt"]["15"]["inputs"]["audio"] == ["11", 3]
|
||||
assert attempt["assumptions"]["source_frontend_declaration"] is None
|
||||
assert source == original and convert(source).prompt is None
|
||||
assert convert_reference(source, SEPARATION_PROFILE).prompt is None
|
||||
|
||||
|
||||
def test_real_split_keeps_unexplained_preview_output_and_whole_graph_closed():
|
||||
source = graph(SPLIT_PROFILE)
|
||||
original = copy.deepcopy(source)
|
||||
assert serialize_reference_widgets(node(source, 2), SPLIT_PROFILE) == dict(
|
||||
zip(LAYOUTS["GuHaiAutoImageSplit"], node(source, 2)["widgets_values"])
|
||||
)
|
||||
attempt = audit.profile_attempt(source, SPLIT_PROFILE)
|
||||
assert attempt["status"] == "rejected" and "candidate_prompt" not in attempt
|
||||
assert any(i["node_id"] == "3" and "输出槽" in i["message"] for i in attempt["issues"])
|
||||
assert convert_reference(source, SPLIT_PROFILE).prompt is None
|
||||
assert source == original and convert(source).prompt is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"start,end",
|
||||
[
|
||||
("12", "60"),
|
||||
("0:01", "0:59"),
|
||||
("-1", "0"),
|
||||
("0:00", "0:00"),
|
||||
("1:90", "999:00"),
|
||||
(" 2 ", "+30"),
|
||||
],
|
||||
)
|
||||
def test_crop_saved_strings_propagate_without_time_parse_clamp_or_round(start, end):
|
||||
source = graph(CROP_PROFILE)
|
||||
node(source, 18)["widgets_values"] = [start, end]
|
||||
prompt = convert_reference(source, CROP_PROFILE).prompt
|
||||
assert prompt["18"]["inputs"]["start_time"] == start
|
||||
assert prompt["18"]["inputs"]["end_time"] == end
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"bad", [True, False, None, 0, 1.25, float("nan"), float("inf"), [], {}, "%date%", "{1|2}"]
|
||||
)
|
||||
@pytest.mark.parametrize("index", [0, 1])
|
||||
def test_crop_rejects_nonstring_or_dynamic_value_whole_graph(index, bad):
|
||||
source = graph(CROP_PROFILE)
|
||||
node(source, 18)["widgets_values"][index] = bad
|
||||
assert convert_reference(source, CROP_PROFILE).prompt is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fmt", ["PNG", "JPG"])
|
||||
@pytest.mark.parametrize("counts,trim,edge", [((1, 2), 0, False), ((2048, 2048), 2048, True)])
|
||||
def test_synthetic_split_full_contract_unicode_and_values_propagate(fmt, counts, trim, edge):
|
||||
source = synthetic_split()
|
||||
node(source, 2)["widgets_values"] = ["目录/子目录", *counts, edge, trim, "新 前缀_", fmt]
|
||||
attempt = audit.profile_attempt(source, SPLIT_PROFILE)
|
||||
assert attempt["status"] == "complete_reference_candidate"
|
||||
independently_check(source, attempt)
|
||||
actual = attempt["candidate_prompt"]["2"]["inputs"]
|
||||
assert actual["图像"] == ["1", 0]
|
||||
assert actual["保存目录"] == "目录/子目录" and actual["保存格式"] == fmt
|
||||
# Serialized path is just data. No directories/files/rendering were executed.
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"index,bad",
|
||||
[
|
||||
(0, None),
|
||||
(0, "%date%"),
|
||||
(1, True),
|
||||
(1, 0),
|
||||
(1, 2049),
|
||||
(1, 2.0),
|
||||
(2, -1),
|
||||
(2, False),
|
||||
(2, float("inf")),
|
||||
(3, 1),
|
||||
(3, None),
|
||||
(4, -1),
|
||||
(4, True),
|
||||
(4, 2049),
|
||||
(5, []),
|
||||
(5, "{x}"),
|
||||
(6, "png"),
|
||||
(6, "JPEG"),
|
||||
],
|
||||
)
|
||||
def test_synthetic_split_bad_types_enums_and_ui_bounds_fail_closed(index, bad):
|
||||
source = synthetic_split()
|
||||
node(source, 2)["widgets_values"][index] = bad
|
||||
assert convert_reference(source, SPLIT_PROFILE).prompt is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("profile", CROP_SPLIT_PROFILES)
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
"version",
|
||||
"provider",
|
||||
"extra_provider",
|
||||
"missing_provider",
|
||||
"widget_extra",
|
||||
"widget_missing",
|
||||
"widget_binding",
|
||||
"socket_type",
|
||||
"socket_order",
|
||||
"output_index",
|
||||
"output_extra",
|
||||
"output_name",
|
||||
"slot",
|
||||
"bool_slot",
|
||||
"reciprocal",
|
||||
"link_type",
|
||||
"mode",
|
||||
"bool_mode",
|
||||
"serializer",
|
||||
"named",
|
||||
"ue_widget",
|
||||
"ue_link",
|
||||
"frontend",
|
||||
"unknown_node",
|
||||
"dynamic",
|
||||
],
|
||||
)
|
||||
def test_strict_contract_mutations_close_all_nodes(profile, mutation):
|
||||
source = graph(profile) if profile == CROP_PROFILE else synthetic_split()
|
||||
target = node(source, 18 if profile == CROP_PROFILE else 2)
|
||||
props = target["properties"]
|
||||
provider_key = "cnr_id" if profile == CROP_PROFILE else "aux_id"
|
||||
if mutation == "version":
|
||||
props["ver"] = "0.11.0"
|
||||
elif mutation == "provider":
|
||||
props[provider_key] = "different/provider"
|
||||
elif mutation == "extra_provider":
|
||||
props["aux_id" if profile == CROP_PROFILE else "cnr_id"] = "other"
|
||||
elif mutation == "missing_provider":
|
||||
del props[provider_key]
|
||||
elif mutation == "widget_extra":
|
||||
target["widgets_values"].append(0)
|
||||
elif mutation == "widget_missing":
|
||||
target["widgets_values"].pop()
|
||||
elif mutation == "widget_binding":
|
||||
target["inputs"][1]["widget"] = {"name": "wrong"}
|
||||
elif mutation == "socket_type":
|
||||
target["inputs"][1]["type"] = "FLOAT"
|
||||
elif mutation == "socket_order":
|
||||
target["inputs"][1:3] = target["inputs"][1:3][::-1]
|
||||
elif mutation == "output_index":
|
||||
target["outputs"][0]["slot_index"] = 1
|
||||
elif mutation == "output_extra":
|
||||
target["outputs"].append(copy.deepcopy(target["outputs"][0]))
|
||||
elif mutation == "output_name":
|
||||
target["outputs"][0]["name"] = "other"
|
||||
elif mutation == "slot":
|
||||
source["links"][0][2] = 9
|
||||
elif mutation == "bool_slot":
|
||||
source["links"][0][2] = False
|
||||
elif mutation == "reciprocal":
|
||||
target["inputs"][0]["link"] = None
|
||||
elif mutation == "link_type":
|
||||
source["links"][0][5] = "wrong"
|
||||
elif mutation == "mode":
|
||||
target["mode"] = 2
|
||||
elif mutation == "bool_mode":
|
||||
target["mode"] = False
|
||||
elif mutation == "serializer":
|
||||
props["serializeValue"] = "override"
|
||||
elif mutation == "named":
|
||||
target["widgets_values_named"] = {}
|
||||
elif mutation == "ue_widget":
|
||||
props["ue_properties"]["widget_ue_connectable"] = {"x": True}
|
||||
elif mutation == "ue_link":
|
||||
source["extra"]["ue_links"] = [[1]]
|
||||
elif mutation == "frontend":
|
||||
source["extra"]["frontendVersion"] = "1.53.6"
|
||||
elif mutation == "unknown_node":
|
||||
target["type"] = "unknown"
|
||||
elif mutation == "dynamic":
|
||||
target["widgets_values"][0] = "{a|b}"
|
||||
result = convert_reference(source, profile)
|
||||
assert result.prompt is None and result.issues
|
||||
|
||||
|
||||
@pytest.mark.parametrize("profile", CROP_SPLIT_PROFILES)
|
||||
def test_two_disjoint_instances_preserve_nodes_links_and_values(profile):
|
||||
source = graph(profile) if profile == CROP_PROFILE else synthetic_split()
|
||||
second = copy.deepcopy(source)
|
||||
for n in second["nodes"]:
|
||||
n["id"] += 100
|
||||
for s in n["inputs"]:
|
||||
if s.get("link") is not None:
|
||||
s["link"] += 100
|
||||
for s in n["outputs"]:
|
||||
if s.get("links"):
|
||||
s["links"] = [x + 100 for x in s["links"]]
|
||||
for link in second["links"]:
|
||||
for i in (0, 1, 3):
|
||||
link[i] += 100
|
||||
target = node(second, 118 if profile == CROP_PROFILE else 102)
|
||||
target["widgets_values"][0] = "15" if profile == CROP_PROFILE else "不同目录"
|
||||
source["nodes"].extend(second["nodes"])
|
||||
source["links"].extend(second["links"])
|
||||
result = convert_reference(source, profile)
|
||||
assert result.prompt is not None
|
||||
independently_check(source, audit.profile_attempt(source, profile))
|
||||
assert len(result.prompt) == len(source["nodes"])
|
||||
|
||||
|
||||
def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged():
|
||||
profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in CROP_SPLIT_PROFILES)
|
||||
historical = json.loads((REPO / "docs/hel-892/separation-evidence/library.json").read_bytes())
|
||||
baseline = audit.audit_library(REPO, profiles)
|
||||
current = audit.audit_library(REPO)
|
||||
assert baseline["gap_groups"] == historical["gap_groups"]
|
||||
assert len(profiles) == 14 and len(audit.REFERENCE_PROFILES) == 16
|
||||
assert current["coverage_delta"]["baseline_profiles"] == list(profiles)
|
||||
assert current["coverage_delta"]["new_complete_paths"] == [CROP]
|
||||
assert len(current["coverage_delta"]["current_complete_paths"]) == 8
|
||||
for old, before, after in zip(historical["cases"], baseline["cases"], current["cases"]):
|
||||
assert old["attempts"] == before["attempts"] == after["attempts"][:-2]
|
||||
assert old.get("comparisons") == before.get("comparisons")
|
||||
assert old.get("comparisons") == [
|
||||
c for c in after.get("comparisons", []) if c["profile"] in profiles
|
||||
] or (old.get("comparisons") is None and "comparisons" not in after)
|
||||
if after["source_path"] in (CROP, SPLIT):
|
||||
assert after["comparison_status"] == "comparison_unavailable"
|
||||
assert not after["production_prompt_available"] and not after["execution_verified"]
|
||||
|
||||
def unavailable(r):
|
||||
return {
|
||||
x["source_path"]
|
||||
for x in r["cases"]
|
||||
if all(a["status"] == "not_applicable" for a in x["attempts"])
|
||||
}
|
||||
|
||||
assert unavailable(baseline) == unavailable(current) and len(unavailable(current)) == 98
|
||||
@@ -255,16 +255,20 @@ def test_library_actual_delta_keeps_old_candidates_and_no_golden_claim():
|
||||
tuple(
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in MEDIA_PROFILES and p != audit.SEPARATION_PROFILE
|
||||
if p not in (*MEDIA_PROFILES, audit.SEPARATION_PROFILE, *audit.CROP_SPLIT_PROFILES)
|
||||
),
|
||||
)
|
||||
current = audit.audit_library(
|
||||
REPO,
|
||||
tuple(p for p in audit.REFERENCE_PROFILES if p != audit.SEPARATION_PROFILE),
|
||||
tuple(
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in (audit.SEPARATION_PROFILE, *audit.CROP_SPLIT_PROFILES)
|
||||
),
|
||||
baseline_profiles=tuple(
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in MEDIA_PROFILES and p != audit.SEPARATION_PROFILE
|
||||
if p not in (*MEDIA_PROFILES, audit.SEPARATION_PROFILE, *audit.CROP_SPLIT_PROFILES)
|
||||
),
|
||||
)
|
||||
assert (
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
{
|
||||
"authority": "public_reference_only_not_object_info",
|
||||
"source_manifests": [
|
||||
"crop-split-reference/sources.json",
|
||||
"separation-reference/sources.json",
|
||||
"serialization-evidence/sources.json"
|
||||
],
|
||||
"frontend": {
|
||||
"selected_version": "1.37.11",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"source_declaration": null,
|
||||
"selection": "explicit reference assumption only",
|
||||
"unmodified_widgets_and_extensions": "assumed",
|
||||
"UE_match": "unknown",
|
||||
"target_match": "unknown"
|
||||
},
|
||||
"facts_file": "verified-facts.json",
|
||||
"contracts": {
|
||||
"AudioCrop": {
|
||||
"fixed_original": "crop.py",
|
||||
"definition_lines": [
|
||||
7,
|
||||
77
|
||||
],
|
||||
"schema": {
|
||||
"required": {
|
||||
"audio": [
|
||||
"AUDIO"
|
||||
],
|
||||
"start_time": [
|
||||
"STRING",
|
||||
{
|
||||
"default": "0:00"
|
||||
}
|
||||
],
|
||||
"end_time": [
|
||||
"STRING",
|
||||
{
|
||||
"default": "1:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"widget_layout": [
|
||||
"start_time",
|
||||
"end_time"
|
||||
],
|
||||
"return_types": [
|
||||
"AUDIO"
|
||||
],
|
||||
"saved_values_policy": "identity only; no queue hooks, callback, plugin execution or file operations",
|
||||
"interpretation": {
|
||||
"time_type": "STRING, not FLOAT/INT",
|
||||
"defaults": [
|
||||
"0:00",
|
||||
"1:00"
|
||||
],
|
||||
"units_basis": "source main: minutes*60+seconds; no colon prepends 00:; both parts int()",
|
||||
"special_behavior": "negative frames clamp to 0; >=length clamp to length-1; start>end raises; equal may yield empty slice; end excluded; retains sample_rate",
|
||||
"range": "no numeric min/max declared; 0..2048 inapplicable to these STRING widgets",
|
||||
"runtime_unknown": "syntax/content parsing and sample length not executed/validated; preserved strings do not imply executable audio"
|
||||
}
|
||||
},
|
||||
"GuHaiAutoImageSplit": {
|
||||
"fixed_original": "guhai__nodes__自动分割图像.py",
|
||||
"definition_lines": [
|
||||
54,
|
||||
163
|
||||
],
|
||||
"schema": {
|
||||
"required": {
|
||||
"图像": [
|
||||
"IMAGE"
|
||||
],
|
||||
"保存目录": [
|
||||
"STRING",
|
||||
{
|
||||
"default": "output"
|
||||
}
|
||||
],
|
||||
"水平张数": [
|
||||
"INT",
|
||||
{
|
||||
"default": 4,
|
||||
"min": 1
|
||||
}
|
||||
],
|
||||
"垂直张数": [
|
||||
"INT",
|
||||
{
|
||||
"default": 2,
|
||||
"min": 1
|
||||
}
|
||||
],
|
||||
"移除画布边缘": [
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"移除描边": [
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0
|
||||
}
|
||||
],
|
||||
"文件名前缀": [
|
||||
"STRING",
|
||||
{
|
||||
"default": "孤海图像分割_"
|
||||
}
|
||||
],
|
||||
"保存格式": [
|
||||
[
|
||||
"PNG",
|
||||
"JPG"
|
||||
],
|
||||
{
|
||||
"default": "PNG"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"widget_layout": [
|
||||
"保存目录",
|
||||
"水平张数",
|
||||
"垂直张数",
|
||||
"移除画布边缘",
|
||||
"移除描边",
|
||||
"文件名前缀",
|
||||
"保存格式"
|
||||
],
|
||||
"return_types": [
|
||||
"IMAGE"
|
||||
],
|
||||
"saved_values_policy": "identity only; no queue hooks, callback, plugin execution or file operations",
|
||||
"interpretation": {
|
||||
"provider": "aux_id=goohai/Goohaitools-comfyui; cnr_id absent; ver=885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"numeric_bounds": "plugin minima 1/1/0; selected frontend useIntWidget default max2048; profile subset only, no callback rounding",
|
||||
"algorithm": "uses 图像[0]; optional four-corner median background threshold30 edge scan; integer floor grid; rows outer/columns inner; optional per-tile min(trim,w//2-1,h//2-1) crop",
|
||||
"saving": "joins output directory and 保存目录; creates directory; numbered prefix from existing files; blank prefix falls back only at plugin execution; PNG or JPG/JPEG quality95",
|
||||
"returns": "one IMAGE slot with torch.cat tiles batch; writes files as side effect, no UI/history descriptor in this node",
|
||||
"paths": "literal parameters only; existence/permissions/fonts/resources/actual UE unknown, no paths executed",
|
||||
"actual_graph_blocker": {
|
||||
"node": "3 PreviewImage@comfy-core0.21.1",
|
||||
"source_pointer": "/nodes/0/outputs",
|
||||
"source_types": [
|
||||
"IMAGE"
|
||||
],
|
||||
"fixed_core_types": [],
|
||||
"fixed_definition": "serialization-evidence/corev0.21.1__nodes.py:1608-1680; inherits SaveImage.RETURN_TYPES=()",
|
||||
"policy": "prompt=None for whole actual graph; no dropping the unexplained output; synthetic fixture separate"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import torch
|
||||
|
||||
from typing import Tuple
|
||||
from ._types import AUDIO
|
||||
|
||||
|
||||
class AudioCrop:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"audio": ("AUDIO",),
|
||||
"start_time": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "0:00",
|
||||
},
|
||||
),
|
||||
"end_time": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "1:00",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
FUNCTION = "main"
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
CATEGORY = "audio"
|
||||
DESCRIPTION = "Crop (trim) audio to a specific start and end time."
|
||||
|
||||
def main(
|
||||
self,
|
||||
audio: AUDIO,
|
||||
start_time: str = "0:00",
|
||||
end_time: str = "1:00",
|
||||
) -> Tuple[AUDIO]:
|
||||
|
||||
waveform: torch.Tensor = audio["waveform"]
|
||||
sample_rate: int = audio["sample_rate"]
|
||||
|
||||
# Assume that no ":" in input means that the user is trying to specify seconds
|
||||
if ":" not in start_time:
|
||||
start_time = f"00:{start_time}"
|
||||
if ":" not in end_time:
|
||||
end_time = f"00:{end_time}"
|
||||
|
||||
start_seconds_time = 60 * int(start_time.split(":")[0]) + int(
|
||||
start_time.split(":")[1]
|
||||
)
|
||||
start_frame = start_seconds_time * sample_rate
|
||||
if start_frame >= waveform.shape[-1]:
|
||||
start_frame = waveform.shape[-1] - 1
|
||||
|
||||
end_seconds_time = 60 * int(end_time.split(":")[0]) + int(
|
||||
end_time.split(":")[1]
|
||||
)
|
||||
end_frame = end_seconds_time * sample_rate
|
||||
if end_frame >= waveform.shape[-1]:
|
||||
end_frame = waveform.shape[-1] - 1
|
||||
if start_frame < 0:
|
||||
start_frame = 0
|
||||
if end_frame < 0:
|
||||
end_frame = 0
|
||||
|
||||
if start_frame > end_frame:
|
||||
raise ValueError(
|
||||
"AudioCrop: Start time must be less than end time and be within the audio length."
|
||||
)
|
||||
|
||||
return (
|
||||
{
|
||||
"waveform": waveform[..., start_frame:end_frame],
|
||||
"sample_rate": sample_rate,
|
||||
},
|
||||
)
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
git clone https://github.com/goohai/Goohaitools-comfyui.git
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 获取当前包目录的路径
|
||||
current_dir = Path(__file__).parent
|
||||
nodes_dir = current_dir / "nodes"
|
||||
|
||||
# 设置WEB目录路径 - 这是关键配置
|
||||
WEB_DIRECTORY = "./web"
|
||||
|
||||
# 初始化全局映射字典
|
||||
NODE_CLASS_MAPPINGS = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
# 遍历nodes目录中的所有Python文件
|
||||
for file_path in nodes_dir.glob("*.py"):
|
||||
# 跳过__init__.py文件
|
||||
if file_path.name == "__init__.py":
|
||||
continue
|
||||
|
||||
# 提取模块名(不含.py后缀)
|
||||
module_name = file_path.stem
|
||||
|
||||
# 使用importlib动态加载模块
|
||||
spec = importlib.util.spec_from_file_location(f"goohaitools.nodes.{module_name}", file_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
|
||||
try:
|
||||
# 执行模块代码
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
# 检查并合并NODE_CLASS_MAPPINGS
|
||||
if hasattr(module, 'NODE_CLASS_MAPPINGS'):
|
||||
NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS)
|
||||
|
||||
# 检查并合并NODE_DISPLAY_NAME_MAPPINGS
|
||||
if hasattr(module, 'NODE_DISPLAY_NAME_MAPPINGS'):
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error loading node module {module_name}: {str(e)}")
|
||||
continue
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
|
||||
|
||||
# 打印加载信息
|
||||
print(f'\033[92m[GoohaiTools]\033[0m \033[93m{len(NODE_CLASS_MAPPINGS)} nodes\033[0m loaded | \033[94mColorWidget enabled\033[0m')
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"title": "Goohaitools-comfyui",
|
||||
"description": "孤海ComfyUI自定义节点合集,批处理实用工具箱。",
|
||||
"author": "goohai",
|
||||
"tags": ["孤海", "tool", "utility", "image-processing", "face-detection"],
|
||||
"install_mode": "copy",
|
||||
"files": [
|
||||
{
|
||||
"src": "nodes/*.py",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/nodes/"
|
||||
},
|
||||
{
|
||||
"src": "fonts/",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/fonts/"
|
||||
},
|
||||
{
|
||||
"src": "requirements.txt",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/"
|
||||
},
|
||||
{
|
||||
"src": "shape_predictor_5_face_landmarks.dat",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/"
|
||||
},
|
||||
{
|
||||
"src": "__init__.py",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/"
|
||||
},
|
||||
{
|
||||
"src": "extension.json",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/"
|
||||
},
|
||||
{
|
||||
"src": ".gitignore",
|
||||
"dst": "custom_nodes/Goohaitools-comfyui/"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import os
|
||||
import re
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import torch
|
||||
import folder_paths
|
||||
|
||||
def auto_crop_image(image):
|
||||
img = image.convert("RGB")
|
||||
img_array = np.array(img)
|
||||
|
||||
# 检测背景颜色(取四个角的颜色)
|
||||
corners = [
|
||||
img_array[0, 0],
|
||||
img_array[0, -1],
|
||||
img_array[-1, 0],
|
||||
img_array[-1, -1]
|
||||
]
|
||||
bg_color = np.median(corners, axis=0)
|
||||
|
||||
# 定义颜色差异阈值
|
||||
threshold = 30
|
||||
|
||||
# 上边界
|
||||
top = 0
|
||||
for row in img_array:
|
||||
if np.any(np.abs(row - bg_color) > threshold):
|
||||
break
|
||||
top += 1
|
||||
|
||||
# 下边界
|
||||
bottom = img_array.shape[0] - 1
|
||||
for row in reversed(img_array):
|
||||
if np.any(np.abs(row - bg_color) > threshold):
|
||||
break
|
||||
bottom -= 1
|
||||
|
||||
# 左边界
|
||||
left = 0
|
||||
for col in img_array.transpose(1, 0, 2):
|
||||
if np.any(np.abs(col - bg_color) > threshold):
|
||||
break
|
||||
left += 1
|
||||
|
||||
# 右边界
|
||||
right = img_array.shape[1] - 1
|
||||
for col in reversed(img_array.transpose(1, 0, 2)):
|
||||
if np.any(np.abs(col - bg_color) > threshold):
|
||||
break
|
||||
right -= 1
|
||||
|
||||
return img.crop((left, top, right+1, bottom+1))
|
||||
|
||||
class GuHaiAutoImageSplit:
|
||||
CATEGORY = "孤海工具箱"
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("分割图像",)
|
||||
FUNCTION = "split_image"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"图像": ("IMAGE",),
|
||||
"保存目录": ("STRING", {"default": "output"}),
|
||||
"水平张数": ("INT", {"default": 4, "min": 1}),
|
||||
"垂直张数": ("INT", {"default": 2, "min": 1}),
|
||||
"移除画布边缘": ("BOOLEAN", {"default": True}),
|
||||
"移除描边": ("INT", {"default": 0, "min": 0}),
|
||||
"文件名前缀": ("STRING", {"default": "孤海图像分割_"}),
|
||||
"保存格式": (["PNG", "JPG"], {"default": "PNG"}),
|
||||
}
|
||||
}
|
||||
|
||||
def split_image(self, 图像, 保存目录, 水平张数, 垂直张数, 移除画布边缘, 移除描边, 文件名前缀, 保存格式):
|
||||
# 处理空文件名前缀
|
||||
if not 文件名前缀.strip():
|
||||
文件名前缀 = "孤海图像分割_"
|
||||
|
||||
# 转换张量为PIL图像
|
||||
img_tensor = 图像[0].cpu().numpy()
|
||||
img_array = np.clip(img_tensor * 255.0, 0, 255).astype(np.uint8)
|
||||
img = Image.fromarray(img_array)
|
||||
|
||||
# 根据开关处理图像
|
||||
if 移除画布边缘:
|
||||
processed_img = auto_crop_image(img)
|
||||
else:
|
||||
processed_img = img # 直接使用原始图像
|
||||
|
||||
img_width, img_height = processed_img.size
|
||||
|
||||
# 计算分块尺寸
|
||||
tile_width = img_width // 水平张数
|
||||
tile_height = img_height // 垂直张数
|
||||
|
||||
# 创建保存目录
|
||||
full_path = os.path.join(folder_paths.get_output_directory(), 保存目录)
|
||||
os.makedirs(full_path, exist_ok=True)
|
||||
|
||||
# 处理保存格式
|
||||
format_map = {
|
||||
"JPG": ("JPEG", "jpg"),
|
||||
"PNG": ("PNG", "png")
|
||||
}
|
||||
save_format, ext = format_map[保存格式]
|
||||
save_args = {"format": save_format}
|
||||
if save_format == "JPEG":
|
||||
save_args["quality"] = 95
|
||||
|
||||
# 获取现有文件最大编号
|
||||
max_counter = 0
|
||||
pattern = re.compile(rf"^{re.escape(文件名前缀)}(\d{{2,}})\.{ext}$", re.IGNORECASE)
|
||||
for filename in os.listdir(full_path):
|
||||
match = pattern.match(filename)
|
||||
if match:
|
||||
current_num = int(match.group(1))
|
||||
if current_num > max_counter:
|
||||
max_counter = current_num
|
||||
|
||||
# 分割并保存图像
|
||||
output_images = []
|
||||
counter = max_counter + 1
|
||||
for y in range(垂直张数):
|
||||
for x in range(水平张数):
|
||||
# 计算原始分块位置
|
||||
left = x * tile_width
|
||||
upper = y * tile_height
|
||||
right = left + tile_width
|
||||
lower = upper + tile_height
|
||||
|
||||
# 裁剪原始分块
|
||||
tile = processed_img.crop((left, upper, right, lower))
|
||||
|
||||
# 应用移除描边
|
||||
if 移除描边 > 0:
|
||||
w, h = tile.size
|
||||
# 确保裁剪后尺寸有效
|
||||
trim_size = min(移除描边, w//2-1, h//2-1)
|
||||
if trim_size > 0:
|
||||
tile = tile.crop((
|
||||
trim_size,
|
||||
trim_size,
|
||||
w - trim_size,
|
||||
h - trim_size
|
||||
))
|
||||
|
||||
# 转换模式兼容JPG
|
||||
if save_format == "JPEG" and tile.mode in ("RGBA", "LA"):
|
||||
tile = tile.convert("RGB")
|
||||
|
||||
# 生成文件名
|
||||
filename = f"{文件名前缀}{counter:02d}.{ext}"
|
||||
save_path = os.path.join(full_path, filename)
|
||||
tile.save(save_path, **save_args)
|
||||
|
||||
# 转换回张量格式
|
||||
tile_np = np.array(tile).astype(np.float32) / 255.0
|
||||
tile_tensor = torch.from_numpy(tile_np).unsqueeze(0)
|
||||
output_images.append(tile_tensor)
|
||||
counter += 1
|
||||
|
||||
return (torch.cat(output_images, dim=0),)
|
||||
|
||||
# 节点注册
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"GuHaiAutoImageSplit": GuHaiAutoImageSplit
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"GuHaiAutoImageSplit": "孤海自动分割图像"
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════
|
||||
* 布尔开关 — 替换 "布尔 孤海" 节点原生 checkbox
|
||||
* ═══════════════════════════════════════════════════════════ */
|
||||
|
||||
app.registerExtension({
|
||||
name: "goohaitools.bool_switch",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "布尔孤海") return;
|
||||
|
||||
const origOnCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
origOnCreated?.apply(this, arguments);
|
||||
|
||||
/* ── 设置默认节点颜色(仅首次创建时) ── */
|
||||
this.color = "#4F4047";
|
||||
this.bgcolor = "#493C42";
|
||||
buildCustomSwitch(this);
|
||||
};
|
||||
|
||||
const origOnConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origOnConfigure?.apply(this, arguments);
|
||||
if (this._guhaiSyncUI) this._guhaiSyncUI();
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
/* ────────────────────────────────────────────────────────────
|
||||
* 构建自定义开关(Canvas 绘制,非 DOM)
|
||||
* ──────────────────────────────────────────────────────────── */
|
||||
function buildCustomSwitch(node) {
|
||||
const boolWidget = node.widgets?.find((w) => w.name === "开关");
|
||||
if (!boolWidget) return;
|
||||
|
||||
boolWidget.hidden = true;
|
||||
|
||||
let isOn = !!boolWidget.value;
|
||||
let labelText = (node.properties && node.properties.guhai_label) || "开关";
|
||||
let lastClickTime = 0;
|
||||
let activeInput = null;
|
||||
let _w = 200, _y = 0, _h = 44;
|
||||
|
||||
/* ── 圆角矩形辅助 ── */
|
||||
function rrect(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||
ctx.arcTo(x, y + h, x, y, r);
|
||||
ctx.arcTo(x, y, x + w, y, r);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
/* ── 文本截断辅助 ── */
|
||||
function ellipsis(ctx, text, maxW) {
|
||||
if (ctx.measureText(text).width <= maxW) return text;
|
||||
let t = text;
|
||||
while (t.length > 1 && ctx.measureText(t + "…").width > maxW) {
|
||||
t = t.slice(0, -1);
|
||||
}
|
||||
return t + "…";
|
||||
}
|
||||
|
||||
/* ── 结束标签编辑 ── */
|
||||
function finishEdit() {
|
||||
if (!activeInput) return;
|
||||
labelText = activeInput.value.trim() || "开关";
|
||||
activeInput.remove();
|
||||
activeInput = null;
|
||||
try {
|
||||
node.properties = node.properties || {};
|
||||
node.properties.guhai_label = labelText;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/* ── 开始标签编辑 ── */
|
||||
function startLabelEdit(clientX, clientY) {
|
||||
if (activeInput) return;
|
||||
|
||||
const scale = app.canvas?.ds?.scale ?? 1;
|
||||
const input = document.createElement("input");
|
||||
input.type = "text";
|
||||
input.value = labelText;
|
||||
Object.assign(input.style, {
|
||||
position: "fixed",
|
||||
left: clientX + "px",
|
||||
top: (clientY - 14 * scale) + "px",
|
||||
fontSize: Math.max(12, Math.round(20 * scale)) + "px",
|
||||
fontWeight: "bold",
|
||||
color: "#e0e0e0",
|
||||
background: "#2a2a2a",
|
||||
border: "1px solid #555",
|
||||
borderRadius: "4px",
|
||||
padding: "2px 6px",
|
||||
outline: "none",
|
||||
zIndex: "99999",
|
||||
minWidth: "80px",
|
||||
});
|
||||
|
||||
document.body.appendChild(input);
|
||||
activeInput = input;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
input.focus();
|
||||
input.select();
|
||||
});
|
||||
|
||||
input.addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Enter" || ev.key === "Escape") {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
finishEdit();
|
||||
}
|
||||
}, true);
|
||||
|
||||
input.addEventListener("blur", () => {
|
||||
setTimeout(finishEdit, 50);
|
||||
});
|
||||
}
|
||||
|
||||
/* ════════════════════════════════════════════════════════
|
||||
* 注册 Canvas 自定义 Widget
|
||||
* ════════════════════════════════════════════════════════ */
|
||||
node.addCustomWidget({
|
||||
name: "guhai_toggle",
|
||||
type: "toggle_custom",
|
||||
value: isOn,
|
||||
|
||||
/* ── 每帧绘制 ── */
|
||||
draw(ctx, node, widgetWidth, y, H) {
|
||||
_w = widgetWidth;
|
||||
_y = y;
|
||||
_h = H;
|
||||
|
||||
const m = 10;
|
||||
const yOff = 6;
|
||||
const xOff = 6;
|
||||
|
||||
/* ─ 开关轨道 ─ */
|
||||
const tw = 72, th = 28;
|
||||
const tx = widgetWidth - tw - m - xOff;
|
||||
const ty = y + yOff + (H - th) / 2;
|
||||
|
||||
/* ─ 标签文字:在按钮左侧区域内水平居中 ─ */
|
||||
const textAreaRight = tx - m;
|
||||
const textAreaCenter = (m + textAreaRight) / 2;
|
||||
const maxTextW = textAreaRight - m;
|
||||
|
||||
ctx.font = "bold 24px sans-serif";
|
||||
ctx.fillStyle = "#e0e0e0";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(
|
||||
ellipsis(ctx, labelText, maxTextW),
|
||||
textAreaCenter,
|
||||
y + yOff + H / 2
|
||||
);
|
||||
|
||||
/* ─ 开关轨道绘制 ─ */
|
||||
ctx.save();
|
||||
if (isOn) {
|
||||
ctx.shadowColor = "rgba(76,175,80,0.4)";
|
||||
ctx.shadowBlur = 10;
|
||||
ctx.fillStyle = "#4CAF50";
|
||||
} else {
|
||||
ctx.fillStyle = "#606060";
|
||||
}
|
||||
rrect(ctx, tx, ty, tw, th, th / 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
/* ─ 圆形旋钮 ─ */
|
||||
const kr = 11;
|
||||
const kx = isOn ? tx + tw - kr - 3 : tx + kr + 3;
|
||||
const ky = ty + th / 2;
|
||||
|
||||
ctx.save();
|
||||
ctx.shadowColor = "rgba(0,0,0,0.3)";
|
||||
ctx.shadowBlur = 4;
|
||||
ctx.fillStyle = isOn ? "#ffffff" : "#999999";
|
||||
ctx.beginPath();
|
||||
ctx.arc(kx, ky, kr, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
},
|
||||
|
||||
/* ── 鼠标事件 ── */
|
||||
mouse(event, pos, node) {
|
||||
if (event.type !== "pointerdown" && event.type !== "mousedown") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const dbl = (now - lastClickTime) < 350;
|
||||
lastClickTime = now;
|
||||
|
||||
/* 双击 → 编辑标签 */
|
||||
if (dbl) {
|
||||
startLabelEdit(event.clientX, event.clientY);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* 单击 → 切换开关 */
|
||||
const toggleStartX = _w - 72 - 10 - 20;
|
||||
if (pos[0] > toggleStartX) {
|
||||
isOn = !isOn;
|
||||
boolWidget.value = isOn;
|
||||
this.value = isOn;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
computeSize(width) {
|
||||
return [width, 44];
|
||||
},
|
||||
});
|
||||
|
||||
/* ── 工作流加载后同步 UI ── */
|
||||
node._guhaiSyncUI = () => {
|
||||
isOn = !!boolWidget.value;
|
||||
labelText = (node.properties && node.properties.guhai_label) || "开关";
|
||||
if (activeInput) finishEdit();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,930 @@
|
||||
/**
|
||||
* 孤海注释 - ComfyUI 自定义文本编辑器节点 *
|
||||
*/
|
||||
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
// ==================== 模块级工具常量与函数 ====================
|
||||
|
||||
// URL 安全字符集(RFC 3986 + 常见字符)
|
||||
const _URL_CHARS = "a-zA-Z0-9._~:/?#\\[\\]@!$&'()*+,;=%\\-";
|
||||
|
||||
// 链接匹配正则
|
||||
const LINK_REGEX = new RegExp(
|
||||
"(\\[\\[(.+?)\\]\\])" +
|
||||
"|(https?:\\/\\/[" + _URL_CHARS + "]+)" +
|
||||
"|(www\\.[" + _URL_CHARS + "]+)",
|
||||
"g"
|
||||
);
|
||||
|
||||
const isChinese = (ch) => /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/.test(ch);
|
||||
const isBreakPoint = (ch) => /[\s\p{P}\p{S}]/u.test(ch);
|
||||
const isPunct = (ch) => /\p{P}|\p{S}/.test(ch);
|
||||
|
||||
const CJK_PUNCT_SET = new Set(
|
||||
',。、!?:;「」『』【】《》()\u201C\u201D\u2018\u2019—…~.'.split('')
|
||||
);
|
||||
const isCJKPunct = (ch) => CJK_PUNCT_SET.has(ch);
|
||||
const isCJKLike = (ch) => isChinese(ch) || isCJKPunct(ch);
|
||||
|
||||
const LINE_START_FORBIDDEN = new Set([
|
||||
',', ',', '.', '。', ';', ';', '!', '!',
|
||||
'\u201D', '\u2019', '」', '』',
|
||||
]);
|
||||
const isLineStartForbidden = (ch) => LINE_START_FORBIDDEN.has(ch);
|
||||
|
||||
// ==================== ComfyUI 字体获取(TTL 缓存) ====================
|
||||
|
||||
let _cachedComfyFont = null;
|
||||
let _cachedFontTime = 0;
|
||||
const FONT_CACHE_TTL = 3000;
|
||||
|
||||
function getComfyUIFont() {
|
||||
const now = Date.now();
|
||||
if (_cachedComfyFont && (now - _cachedFontTime) < FONT_CACHE_TTL) return _cachedComfyFont;
|
||||
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
for (const v of ['--font-family', '--fontFamily', '--p-font-family', '--ui-font-family', '--body-font-family']) {
|
||||
const val = root.getPropertyValue(v).trim();
|
||||
if (val && val !== '' && val !== 'inherit' && val !== 'initial') {
|
||||
_cachedComfyFont = val; _cachedFontTime = now; return val;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sel of ['.p-panelmenu .p-panelmenu-item-content', '.p-panelmenu', '.comfy-multiline-input', '.litegraph .dialog', '.p-button', '#vue-app', '#app']) {
|
||||
const el = document.querySelector(sel);
|
||||
if (el) {
|
||||
const ff = getComputedStyle(el).fontFamily;
|
||||
if (ff && ff.trim() !== '' && !/^["']?serif/i.test(ff.trim())) {
|
||||
_cachedComfyFont = ff; _cachedFontTime = now; return ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const walkTargets = document.querySelectorAll('button, label, span, p, h1, h2, h3, h4, a, li, .p-component');
|
||||
for (const el of walkTargets) {
|
||||
const ff = getComputedStyle(el).fontFamily;
|
||||
if (ff && ff.trim() !== '') {
|
||||
const lower = ff.trim().toLowerCase();
|
||||
if (lower !== 'serif' && !lower.startsWith('serif,')) {
|
||||
_cachedComfyFont = ff; _cachedFontTime = now; return ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_cachedComfyFont = '-apple-system, BlinkMacSystemFont, "Segoe UI", DengXian, Roboto, "Helvetica Neue", "Noto Sans", "Microsoft YaHei", "PingFang SC", sans-serif';
|
||||
_cachedFontTime = now;
|
||||
return _cachedComfyFont;
|
||||
}
|
||||
|
||||
// ==================== 链接解析与字符级换行 ====================
|
||||
|
||||
/**
|
||||
* 将文本解析为语义段落数组
|
||||
*/
|
||||
function parseSegments(text) {
|
||||
LINK_REGEX.lastIndex = 0;
|
||||
const segments = [];
|
||||
let match, last = 0;
|
||||
while ((match = LINK_REGEX.exec(text)) !== null) {
|
||||
if (match.index > last)
|
||||
segments.push({ type: 'text', content: text.substring(last, match.index), url: null });
|
||||
if (match[1] !== undefined) {
|
||||
// [[链接]] 语法
|
||||
segments.push({ type: 'link', content: match[2], url: match[2] });
|
||||
} else if (match[3] !== undefined) {
|
||||
segments.push({ type: 'link', content: match[3], url: match[3] });
|
||||
} else if (match[4] !== undefined) {
|
||||
segments.push({ type: 'link', content: match[4], url: match[4] });
|
||||
}
|
||||
last = match.index + match[0].length;
|
||||
}
|
||||
if (last < text.length)
|
||||
segments.push({ type: 'text', content: text.substring(last), url: null });
|
||||
return segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将语义段落展开为带类型标记的字符数组
|
||||
* 每个元素: { ch, type: 'text'|'link', url: string|null }
|
||||
*/
|
||||
function buildCharList(segments) {
|
||||
const list = [];
|
||||
for (const seg of segments) {
|
||||
for (const ch of seg.content) {
|
||||
list.push({ ch, type: seg.type, url: seg.url });
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对带类型标记的字符数组执行自动换行
|
||||
*/
|
||||
function wrapCharList(ctx, charList, maxWidth) {
|
||||
if (!charList || charList.length === 0) return [[]];
|
||||
|
||||
const lines = [];
|
||||
let line = [];
|
||||
let lineStr = '';
|
||||
|
||||
const rebuild = () => { lineStr = line.map(c => c.ch).join(''); };
|
||||
|
||||
for (let i = 0; i < charList.length; i++) {
|
||||
const c = charList[i];
|
||||
|
||||
if (c.ch === '\n') {
|
||||
lines.push(line);
|
||||
line = [];
|
||||
lineStr = '';
|
||||
continue;
|
||||
}
|
||||
|
||||
const test = lineStr + c.ch;
|
||||
|
||||
if (ctx.measureText(test).width > maxWidth && line.length > 0) {
|
||||
|
||||
if (isCJKLike(c.ch)) {
|
||||
lines.push(line);
|
||||
line = [c];
|
||||
lineStr = c.ch;
|
||||
} else {
|
||||
let lastCJK = -1;
|
||||
for (let k = line.length - 1; k >= 0; k--) {
|
||||
if (isCJKLike(line[k].ch)) { lastCJK = k; break; }
|
||||
}
|
||||
|
||||
if (lastCJK >= 0) {
|
||||
lines.push(line.slice(0, lastCJK + 1));
|
||||
line = [...line.slice(lastCJK + 1), c];
|
||||
rebuild();
|
||||
} else {
|
||||
const limit = Math.min(20, line.length);
|
||||
let bp = -1;
|
||||
for (let j = line.length - 1; j >= line.length - limit; j--) {
|
||||
if (isBreakPoint(line[j].ch)) { bp = j; break; }
|
||||
}
|
||||
|
||||
if (bp >= 0) {
|
||||
lines.push(line.slice(0, bp + 1));
|
||||
line = [...line.slice(bp + 1), c];
|
||||
rebuild();
|
||||
if (line.length > 0 && isPunct(line[0].ch)) {
|
||||
let pEnd = 0;
|
||||
while (pEnd < line.length && isPunct(line[pEnd].ch)) pEnd++;
|
||||
lines[lines.length - 1] = [...lines[lines.length - 1], ...line.slice(0, pEnd)];
|
||||
line = line.slice(pEnd);
|
||||
rebuild();
|
||||
}
|
||||
} else if (isPunct(c.ch)) {
|
||||
lines.push([...line, c]);
|
||||
line = [];
|
||||
lineStr = '';
|
||||
} else {
|
||||
lines.push(line);
|
||||
line = [c];
|
||||
lineStr = c.ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 行首禁排字符
|
||||
let fix = 0;
|
||||
while (fix++ < 20 && line.length > 0 && isLineStartForbidden(line[0].ch) && lines.length > 0) {
|
||||
const prev = lines[lines.length - 1];
|
||||
if (!prev || prev.length <= 1) break;
|
||||
const last = prev[prev.length - 1];
|
||||
if (isCJKLike(last.ch)) {
|
||||
line = [last, ...line];
|
||||
lines[lines.length - 1] = prev.slice(0, -1);
|
||||
} else if (!isBreakPoint(last.ch)) {
|
||||
let ws = prev.length - 1;
|
||||
while (ws > 0 && !isBreakPoint(prev[ws - 1].ch)) ws--;
|
||||
if (ws === 0) {
|
||||
line = [last, ...line];
|
||||
lines[lines.length - 1] = prev.slice(0, -1);
|
||||
} else {
|
||||
line = [...prev.slice(ws), ...line];
|
||||
lines[lines.length - 1] = prev.slice(0, ws);
|
||||
}
|
||||
} else break;
|
||||
rebuild();
|
||||
}
|
||||
} else {
|
||||
line.push(c);
|
||||
lineStr = test;
|
||||
}
|
||||
}
|
||||
|
||||
if (line.length > 0) lines.push(line);
|
||||
return lines.length > 0 ? lines : [[]];
|
||||
}
|
||||
|
||||
// ==================== 基础节点类 ====================
|
||||
|
||||
class TextEditorBaseNode extends LGraphNode {
|
||||
constructor(title) {
|
||||
super(title);
|
||||
this.serialize_widgets = true;
|
||||
this.isVirtualNode = true;
|
||||
this.class_type = this.constructor.type;
|
||||
this.type = this.constructor.type;
|
||||
this.pos = [0, 0];
|
||||
}
|
||||
|
||||
static setUp() {
|
||||
if (!this.registered) {
|
||||
LiteGraph.registerNodeType(this.type, this);
|
||||
this.registered = true;
|
||||
}
|
||||
}
|
||||
|
||||
configure(info) {
|
||||
if (info.properties) Object.assign(this.properties, info.properties);
|
||||
if (info.pos) this.pos = info.pos;
|
||||
if (info.size) this.size = info.size;
|
||||
if (info.flags) this.flags = info.flags;
|
||||
}
|
||||
|
||||
serialize() {
|
||||
const data = super.serialize();
|
||||
if (!data.id && this.id) data.id = this.id;
|
||||
if (!data.order && this.order !== undefined) data.order = this.order;
|
||||
if (!data.mode && this.mode !== undefined) data.mode = this.mode;
|
||||
data.properties = { ...this.properties };
|
||||
if (!data.pos && this.pos) data.pos = [...this.pos];
|
||||
if (!data.size && this.size) data.size = [...this.size];
|
||||
if (!data.flags && this.flags) data.flags = { ...this.flags };
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 文本编辑器节点 ====================
|
||||
|
||||
class TextEditorNode extends TextEditorBaseNode {
|
||||
|
||||
constructor(title) {
|
||||
super(title);
|
||||
this.flags = this.flags || {};
|
||||
this.flags.allow_interaction = !this.flags.pinned;
|
||||
this.properties = {
|
||||
text: "双击编辑文本内容...",
|
||||
fontSize: 24,
|
||||
fontColor: "#E3E3E3",
|
||||
backgroundColor: "#1B4669",
|
||||
backgroundAlpha: 0.6,
|
||||
borderRadius: 30,
|
||||
padding: 12,
|
||||
lineHeight: 1.4,
|
||||
textAlign: "center"
|
||||
};
|
||||
this.resizable = true;
|
||||
this.size = [360, 100];
|
||||
this.color = "#fff0";
|
||||
this.bgcolor = "transparent";
|
||||
this.isEditing = false;
|
||||
this.editTextarea = null;
|
||||
this.linkAreas = [];
|
||||
}
|
||||
|
||||
/* ---------- 字符级多行文本绘制 ---------- */
|
||||
|
||||
drawMultilineText(ctx, text, maxWidth, lineHeight) {
|
||||
this.linkAreas = [];
|
||||
|
||||
|
||||
const processed = text
|
||||
.replace(/\\n/g, "\n")
|
||||
.replace(/\r\n/g, "\n")
|
||||
.replace(/\r/g, "\n");
|
||||
|
||||
const segments = parseSegments(processed);
|
||||
const chars = buildCharList(segments);
|
||||
const lines = wrapCharList(ctx, chars, maxWidth);
|
||||
|
||||
if (lines.length === 0) return;
|
||||
|
||||
const totalHeight = (lines.length - 1) * lineHeight + this.properties.fontSize;
|
||||
const startY = (this.size[1] - totalHeight) / 2 + this.properties.fontSize / 10;
|
||||
ctx.textBaseline = "top";
|
||||
|
||||
for (let idx = 0; idx < lines.length; idx++) {
|
||||
const lineChars = lines[idx];
|
||||
if (lineChars.length === 0) continue;
|
||||
const y = startY + idx * lineHeight;
|
||||
|
||||
|
||||
const groups = [];
|
||||
let gi = 0;
|
||||
while (gi < lineChars.length) {
|
||||
const { type, url } = lineChars[gi];
|
||||
let gj = gi;
|
||||
while (gj < lineChars.length && lineChars[gj].type === type && lineChars[gj].url === url) gj++;
|
||||
groups.push({
|
||||
type, url,
|
||||
text: lineChars.slice(gi, gj).map(c => c.ch).join('')
|
||||
});
|
||||
gi = gj;
|
||||
}
|
||||
|
||||
// 计算行起始 x(根据对齐方式)
|
||||
const totalW = groups.reduce((s, g) => s + ctx.measureText(g.text).width, 0);
|
||||
let startX;
|
||||
if (this.properties.textAlign === "left") {
|
||||
startX = this.properties.padding;
|
||||
} else if (this.properties.textAlign === "right") {
|
||||
startX = this.size[0] - this.properties.padding - totalW;
|
||||
} else {
|
||||
startX = (this.size[0] - totalW) / 2;
|
||||
}
|
||||
|
||||
ctx.textAlign = "left";
|
||||
let dx = startX;
|
||||
|
||||
for (const g of groups) {
|
||||
const w = ctx.measureText(g.text).width;
|
||||
if (g.type === 'link') {
|
||||
this.linkAreas.push({ x: dx, y, width: w, height: lineHeight, url: g.url });
|
||||
ctx.fillStyle = "#1976D2";
|
||||
ctx.fillText(g.text, dx, y);
|
||||
// 下划线
|
||||
const uy = y + this.properties.fontSize;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(dx, uy + 1);
|
||||
ctx.lineTo(dx + w, uy + 1);
|
||||
ctx.strokeStyle = "#1976D2";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
} else {
|
||||
ctx.fillStyle = this.properties.fontColor;
|
||||
ctx.fillText(g.text, dx, y);
|
||||
}
|
||||
dx += w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 编辑器管理 ---------- */
|
||||
|
||||
createTextEditor() {
|
||||
if (this.editTextarea) this.removeTextEditor();
|
||||
|
||||
_cachedFontTime = 0;
|
||||
|
||||
const canvas = LGraphCanvas.active_canvas;
|
||||
const rect = canvas.canvas.getBoundingClientRect();
|
||||
const ox = (this.pos[0] + canvas.ds.offset[0]) * canvas.ds.scale;
|
||||
const oy = (this.pos[1] + canvas.ds.offset[1]) * canvas.ds.scale;
|
||||
|
||||
const TOOLBAR_OFFSET = 190;
|
||||
|
||||
// ---- 工具栏 ----
|
||||
this.editToolbar = document.createElement("div");
|
||||
Object.assign(this.editToolbar.style, {
|
||||
position: "absolute",
|
||||
left: rect.left + ox + "px",
|
||||
top: rect.top + oy - TOOLBAR_OFFSET + "px",
|
||||
width: "373px", display: "flex", flexDirection: "column",
|
||||
gap: "8px", zIndex: "1001", fontSize: "12px", color: "#ffffff"
|
||||
});
|
||||
|
||||
// ---- 对齐 ----
|
||||
const alignRow = document.createElement("div");
|
||||
Object.assign(alignRow.style, { display: "flex", alignItems: "center", gap: "8px" });
|
||||
const alignLabel = document.createElement("span");
|
||||
alignLabel.textContent = "对齐:";
|
||||
alignLabel.style.minWidth = "32px";
|
||||
alignLabel.style.fontSize = "13px";
|
||||
alignRow.appendChild(alignLabel);
|
||||
|
||||
this.alignButtons = {};
|
||||
[
|
||||
{ key: "left", symbol: "⬅" },
|
||||
{ key: "center", symbol: "⬌" },
|
||||
{ key: "right", symbol: "➡" }
|
||||
].forEach((opt) => {
|
||||
const btn = document.createElement("button");
|
||||
btn.textContent = opt.symbol;
|
||||
Object.assign(btn.style, {
|
||||
width: "28px", height: "24px", border: "1px solid #666",
|
||||
borderRadius: "3px", cursor: "pointer", fontSize: "12px",
|
||||
backgroundColor: this.properties.textAlign === opt.key ? "#459BAC" : "#444",
|
||||
color: "#fff", display: "flex", alignItems: "center", justifyContent: "center"
|
||||
});
|
||||
btn.addEventListener("click", () => {
|
||||
this.properties.textAlign = opt.key;
|
||||
this.updateAlignButtons();
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
this.alignButtons[opt.key] = btn;
|
||||
alignRow.appendChild(btn);
|
||||
});
|
||||
this.editToolbar.appendChild(alignRow);
|
||||
|
||||
// ---- 文本(颜色)+ 大小(滑条) ----
|
||||
const textRow = document.createElement("div");
|
||||
Object.assign(textRow.style, { display: "flex", alignItems: "center", gap: "8px" });
|
||||
|
||||
const txtLbl = document.createElement("span");
|
||||
txtLbl.textContent = "文本:";
|
||||
txtLbl.style.minWidth = "32px";
|
||||
txtLbl.style.fontSize = "13px";
|
||||
textRow.appendChild(txtLbl);
|
||||
|
||||
this.textColorPicker = document.createElement("input");
|
||||
this.textColorPicker.type = "color";
|
||||
this.textColorPicker.value = this.properties.fontColor;
|
||||
Object.assign(this.textColorPicker.style, { width: "56px", height: "24px", border: "none", borderRadius: "3px", cursor: "pointer" });
|
||||
this.textColorPicker.addEventListener("change", (e) => {
|
||||
this.properties.fontColor = e.target.value;
|
||||
this.updateTextareaStyle();
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
textRow.appendChild(this.textColorPicker);
|
||||
|
||||
const textSpacer = document.createElement("div");
|
||||
Object.assign(textSpacer.style, { width: "28px", flexShrink: "0", flexGrow: "0" });
|
||||
textRow.appendChild(textSpacer);
|
||||
|
||||
const sizeLbl = document.createElement("span");
|
||||
sizeLbl.textContent = "大小:";
|
||||
sizeLbl.style.fontSize = "13px";
|
||||
textRow.appendChild(sizeLbl);
|
||||
|
||||
this.fontSizeSlider = document.createElement("input");
|
||||
this.fontSizeSlider.type = "range";
|
||||
this.fontSizeSlider.min = "8";
|
||||
this.fontSizeSlider.max = "200";
|
||||
this.fontSizeSlider.value = this.properties.fontSize;
|
||||
Object.assign(this.fontSizeSlider.style, { flex: "1", height: "20px" });
|
||||
this.fontSizeSlider.addEventListener("input", (e) => {
|
||||
this.properties.fontSize = parseInt(e.target.value);
|
||||
this.fontSizeValue.textContent = this.properties.fontSize;
|
||||
this.updateTextareaStyle();
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
textRow.appendChild(this.fontSizeSlider);
|
||||
|
||||
this.fontSizeValue = document.createElement("span");
|
||||
this.fontSizeValue.textContent = this.properties.fontSize;
|
||||
Object.assign(this.fontSizeValue.style, { fontSize: "12px", minWidth: "25px", textAlign: "right" });
|
||||
textRow.appendChild(this.fontSizeValue);
|
||||
this.editToolbar.appendChild(textRow);
|
||||
|
||||
// ---- 背景(颜色)+ 透明(滑条) ----
|
||||
const bgRow = document.createElement("div");
|
||||
Object.assign(bgRow.style, { display: "flex", alignItems: "center", gap: "8px" });
|
||||
|
||||
const bgLbl = document.createElement("span");
|
||||
bgLbl.textContent = "背景:";
|
||||
bgLbl.style.minWidth = "32px";
|
||||
bgLbl.style.fontSize = "13px";
|
||||
bgRow.appendChild(bgLbl);
|
||||
|
||||
this.bgColorPicker = document.createElement("input");
|
||||
this.bgColorPicker.type = "color";
|
||||
this.bgColorPicker.value = this.properties.backgroundColor;
|
||||
Object.assign(this.bgColorPicker.style, { width: "56px", height: "24px", border: "none", borderRadius: "3px", cursor: "pointer" });
|
||||
this.bgColorPicker.addEventListener("change", (e) => {
|
||||
this.properties.backgroundColor = e.target.value;
|
||||
this.updateTextareaStyle();
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
bgRow.appendChild(this.bgColorPicker);
|
||||
|
||||
const bgSpacer = document.createElement("div");
|
||||
Object.assign(bgSpacer.style, { width: "28px", flexShrink: "0", flexGrow: "0" });
|
||||
bgRow.appendChild(bgSpacer);
|
||||
|
||||
const alphaLbl = document.createElement("span");
|
||||
alphaLbl.textContent = "透明:";
|
||||
alphaLbl.style.fontSize = "13px";
|
||||
bgRow.appendChild(alphaLbl);
|
||||
|
||||
this.alphaSlider = document.createElement("input");
|
||||
this.alphaSlider.type = "range";
|
||||
this.alphaSlider.min = "0";
|
||||
this.alphaSlider.max = "1";
|
||||
this.alphaSlider.step = "0.05";
|
||||
this.alphaSlider.value = this.properties.backgroundAlpha;
|
||||
Object.assign(this.alphaSlider.style, { flex: "1", height: "20px" });
|
||||
this.alphaSlider.addEventListener("input", (e) => {
|
||||
this.properties.backgroundAlpha = parseFloat(e.target.value);
|
||||
this.alphaValue.textContent = Math.round(100 * this.properties.backgroundAlpha) + "%";
|
||||
this.updateTextareaStyle();
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
bgRow.appendChild(this.alphaSlider);
|
||||
|
||||
this.alphaValue = document.createElement("span");
|
||||
this.alphaValue.textContent = Math.round(100 * this.properties.backgroundAlpha) + "%";
|
||||
Object.assign(this.alphaValue.style, { fontSize: "12px", minWidth: "25px", textAlign: "right" });
|
||||
bgRow.appendChild(this.alphaValue);
|
||||
this.editToolbar.appendChild(bgRow);
|
||||
|
||||
// ---- 圆角 ----
|
||||
const radiusRow = document.createElement("div");
|
||||
Object.assign(radiusRow.style, { display: "flex", alignItems: "center", gap: "8px" });
|
||||
const radiusLbl = document.createElement("span");
|
||||
radiusLbl.textContent = "圆角:";
|
||||
radiusLbl.style.minWidth = "32px";
|
||||
radiusLbl.style.fontSize = "13px";
|
||||
radiusRow.appendChild(radiusLbl);
|
||||
|
||||
this.borderRadiusSlider = document.createElement("input");
|
||||
this.borderRadiusSlider.type = "range";
|
||||
this.borderRadiusSlider.min = "0";
|
||||
this.borderRadiusSlider.max = "300";
|
||||
this.borderRadiusSlider.value = this.properties.borderRadius;
|
||||
Object.assign(this.borderRadiusSlider.style, { flex: "1", height: "20px" });
|
||||
this.borderRadiusSlider.addEventListener("input", (e) => {
|
||||
this.properties.borderRadius = parseInt(e.target.value);
|
||||
this.borderRadiusValue.textContent = this.properties.borderRadius;
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
radiusRow.appendChild(this.borderRadiusSlider);
|
||||
|
||||
this.borderRadiusValue = document.createElement("span");
|
||||
this.borderRadiusValue.textContent = this.properties.borderRadius;
|
||||
Object.assign(this.borderRadiusValue.style, { fontSize: "12px", minWidth: "25px", textAlign: "right" });
|
||||
radiusRow.appendChild(this.borderRadiusValue);
|
||||
this.editToolbar.appendChild(radiusRow);
|
||||
|
||||
// ---- 行距 ----
|
||||
const lhRow = document.createElement("div");
|
||||
Object.assign(lhRow.style, { display: "flex", alignItems: "center", gap: "8px" });
|
||||
const lhLbl = document.createElement("span");
|
||||
lhLbl.textContent = "行距:";
|
||||
lhLbl.style.minWidth = "32px";
|
||||
lhLbl.style.fontSize = "13px";
|
||||
lhRow.appendChild(lhLbl);
|
||||
|
||||
this.lineHeightSlider = document.createElement("input");
|
||||
this.lineHeightSlider.type = "range";
|
||||
this.lineHeightSlider.min = "0.8";
|
||||
this.lineHeightSlider.max = "3.0";
|
||||
this.lineHeightSlider.step = "0.1";
|
||||
this.lineHeightSlider.value = this.properties.lineHeight;
|
||||
Object.assign(this.lineHeightSlider.style, { flex: "1", height: "20px" });
|
||||
this.lineHeightSlider.addEventListener("input", (e) => {
|
||||
this.properties.lineHeight = parseFloat(e.target.value);
|
||||
this.lineHeightValue.textContent = this.properties.lineHeight.toFixed(1);
|
||||
app.graph.setDirtyCanvas(true);
|
||||
});
|
||||
lhRow.appendChild(this.lineHeightSlider);
|
||||
|
||||
this.lineHeightValue = document.createElement("span");
|
||||
this.lineHeightValue.textContent = this.properties.lineHeight.toFixed(1);
|
||||
Object.assign(this.lineHeightValue.style, { fontSize: "12px", minWidth: "25px", textAlign: "right" });
|
||||
lhRow.appendChild(this.lineHeightValue);
|
||||
this.editToolbar.appendChild(lhRow);
|
||||
|
||||
document.body.appendChild(this.editToolbar);
|
||||
|
||||
// ---- 文本编辑区 ----
|
||||
this.editTextarea = document.createElement("textarea");
|
||||
this.editTextarea.value = this.properties.text;
|
||||
Object.assign(this.editTextarea.style, {
|
||||
position: "absolute",
|
||||
left: rect.left + ox + this.properties.padding * canvas.ds.scale + "px",
|
||||
top: rect.top + oy + 10 * canvas.ds.scale + "px",
|
||||
width: (this.size[0] - 2 * this.properties.padding) * canvas.ds.scale + "px",
|
||||
height: (this.size[1] - 20) * canvas.ds.scale + "px",
|
||||
fontFamily: getComfyUIFont(),
|
||||
border: "none", borderRadius: "0px", outline: "none",
|
||||
resize: "none", padding: "0px", boxSizing: "border-box",
|
||||
zIndex: "1000", textAlign: this.properties.textAlign
|
||||
});
|
||||
this.updateTextareaStyle();
|
||||
document.body.appendChild(this.editTextarea);
|
||||
this.editTextarea.focus();
|
||||
this.editTextarea.select();
|
||||
|
||||
// 保存并关闭
|
||||
const saveAndClose = () => {
|
||||
this.properties.text = this.editTextarea.value;
|
||||
this.removeTextEditor();
|
||||
this.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true);
|
||||
};
|
||||
|
||||
// 位置同步
|
||||
this.updateEditorsPosition = () => {
|
||||
if (!this.editTextarea || !this.editToolbar) return;
|
||||
const c = LGraphCanvas.active_canvas;
|
||||
const r = c.canvas.getBoundingClientRect();
|
||||
const ox2 = (this.pos[0] + c.ds.offset[0]) * c.ds.scale;
|
||||
const oy2 = (this.pos[1] + c.ds.offset[1]) * c.ds.scale;
|
||||
Object.assign(this.editTextarea.style, {
|
||||
left: r.left + ox2 + this.properties.padding * c.ds.scale + "px",
|
||||
top: r.top + oy2 + 10 * c.ds.scale + "px",
|
||||
width: (this.size[0] - 2 * this.properties.padding) * c.ds.scale + "px",
|
||||
height: (this.size[1] - 20) * c.ds.scale + "px"
|
||||
});
|
||||
Object.assign(this.editToolbar.style, {
|
||||
left: r.left + ox2 + "px",
|
||||
top: r.top + oy2 - TOOLBAR_OFFSET + "px"
|
||||
});
|
||||
this.updateTextareaStyle();
|
||||
};
|
||||
|
||||
const origOCC = canvas.onCanvasChanged;
|
||||
canvas.onCanvasChanged = (evt) => {
|
||||
origOCC && origOCC.call(canvas, evt);
|
||||
this.updateEditorsPosition();
|
||||
};
|
||||
this.canvasUpdateInterval = setInterval(() => this.updateEditorsPosition(), 16);
|
||||
|
||||
// 键盘事件
|
||||
this.editTextarea.addEventListener("keydown", (e) => {
|
||||
if ("Escape" === e.key) {
|
||||
this.removeTextEditor();
|
||||
} else if ("Enter" === e.key && (e.ctrlKey || e.metaKey)) {
|
||||
saveAndClose();
|
||||
}
|
||||
e.stopPropagation();
|
||||
});
|
||||
|
||||
// 点击外部自动保存
|
||||
this.clickCount = 0;
|
||||
this.documentClickHandler = (e) => {
|
||||
this.clickCount++;
|
||||
setTimeout(() => {
|
||||
this.clickCount--;
|
||||
if (this.clickCount === 0 && this.editTextarea && this.editToolbar &&
|
||||
!this.editTextarea.contains(e.target) &&
|
||||
!this.editToolbar.contains(e.target) && this.isEditing) {
|
||||
saveAndClose();
|
||||
}
|
||||
}, 300);
|
||||
};
|
||||
setTimeout(() => {
|
||||
if (this.isEditing) document.addEventListener("click", this.documentClickHandler, true);
|
||||
}, 200);
|
||||
|
||||
// 失去焦点
|
||||
this.editTextarea.addEventListener("blur", () => {
|
||||
setTimeout(() => {
|
||||
if (this.editToolbar && this.editTextarea &&
|
||||
!this.editToolbar.contains(document.activeElement) &&
|
||||
document.activeElement !== this.editTextarea) {
|
||||
saveAndClose();
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
this.isEditing = true;
|
||||
}
|
||||
|
||||
updateTextareaStyle() {
|
||||
if (!this.editTextarea) return;
|
||||
const s = LGraphCanvas.active_canvas.ds.scale;
|
||||
Object.assign(this.editTextarea.style, {
|
||||
fontSize: this.properties.fontSize * s + "px",
|
||||
fontFamily: getComfyUIFont(),
|
||||
color: this.properties.fontColor,
|
||||
backgroundColor: this.hexToRGBA(this.properties.backgroundColor, this.properties.backgroundAlpha),
|
||||
textAlign: this.properties.textAlign,
|
||||
lineHeight: this.properties.lineHeight,
|
||||
paddingTop: "2px", paddingLeft: "0px", paddingRight: "0px", paddingBottom: "0px",
|
||||
boxSizing: "border-box"
|
||||
});
|
||||
}
|
||||
|
||||
updateAlignButtons() {
|
||||
Object.keys(this.alignButtons).forEach((k) => {
|
||||
this.alignButtons[k].style.backgroundColor = this.properties.textAlign === k ? "#459BAC" : "#444";
|
||||
});
|
||||
}
|
||||
|
||||
removeTextEditor() {
|
||||
if (this.editTextarea) { document.body.removeChild(this.editTextarea); this.editTextarea = null; }
|
||||
if (this.editToolbar) { document.body.removeChild(this.editToolbar); this.editToolbar = null; }
|
||||
if (this.canvasUpdateInterval) { clearInterval(this.canvasUpdateInterval); this.canvasUpdateInterval = null; }
|
||||
if (this.documentClickHandler) { document.removeEventListener("click", this.documentClickHandler, true); this.documentClickHandler = null; }
|
||||
this.isEditing = false;
|
||||
}
|
||||
|
||||
/* ---------- 渲染 ---------- */
|
||||
|
||||
onDrawBackground(ctx) {
|
||||
ctx.save();
|
||||
ctx.imageSmoothingEnabled = true;
|
||||
|
||||
const r = this.properties.borderRadius;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(0, 0, this.size[0], this.size[1], r);
|
||||
ctx.fillStyle = this.hexToRGBA(this.properties.backgroundColor, this.properties.backgroundAlpha);
|
||||
ctx.fill();
|
||||
|
||||
if (this.isEditing) {
|
||||
ctx.strokeStyle = "#4CAF50";
|
||||
ctx.lineWidth = 2;
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
if (!this.isEditing) {
|
||||
ctx.fillStyle = this.properties.fontColor;
|
||||
ctx.font = this.properties.fontSize + "px " + getComfyUIFont();
|
||||
const lh = this.properties.fontSize * this.properties.lineHeight;
|
||||
const mw = this.size[0] - 2 * this.properties.padding;
|
||||
this.drawMultilineText(ctx, this.properties.text, mw, lh);
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
hexToRGBA(hex, alpha) {
|
||||
return "rgba(" +
|
||||
parseInt(hex.slice(1, 3), 16) + ", " +
|
||||
parseInt(hex.slice(3, 5), 16) + ", " +
|
||||
parseInt(hex.slice(5, 7), 16) + ", " +
|
||||
alpha + ")";
|
||||
}
|
||||
|
||||
draw(ctx) {
|
||||
this.flags = this.flags || {};
|
||||
this.flags.allow_interaction = !this.flags.pinned;
|
||||
this.onDrawBackground(ctx);
|
||||
}
|
||||
|
||||
/* ---------- 属性变更 ---------- */
|
||||
|
||||
onPropertyChanged(name, value) {
|
||||
if (this.isEditing) {
|
||||
if ("fontSize" === name && this.fontSizeSlider) {
|
||||
this.fontSizeSlider.value = value;
|
||||
this.fontSizeValue.textContent = value;
|
||||
} else if ("fontColor" === name && this.textColorPicker) {
|
||||
this.textColorPicker.value = value;
|
||||
} else if ("backgroundColor" === name && this.bgColorPicker) {
|
||||
this.bgColorPicker.value = value;
|
||||
} else if ("backgroundAlpha" === name && this.alphaSlider) {
|
||||
this.alphaSlider.value = value;
|
||||
this.alphaValue.textContent = Math.round(100 * value) + "%";
|
||||
} else if ("lineHeight" === name && this.lineHeightSlider) {
|
||||
this.lineHeightSlider.value = value;
|
||||
this.lineHeightValue.textContent = value.toFixed(1);
|
||||
} else if ("textAlign" === name && this.alignButtons) {
|
||||
this.updateAlignButtons();
|
||||
} else if ("borderRadius" === name && this.borderRadiusSlider) {
|
||||
this.borderRadiusSlider.value = value;
|
||||
this.borderRadiusValue.textContent = value;
|
||||
}
|
||||
this.updateTextareaStyle();
|
||||
}
|
||||
this.setDirtyCanvas(true, true);
|
||||
app.graph.setDirtyCanvas(true);
|
||||
}
|
||||
|
||||
/* ---------- 交互事件 ---------- */
|
||||
|
||||
onMouseDown(evt, pos) {
|
||||
if (!this.isEditing && this.linkAreas && this.linkAreas.length > 0) {
|
||||
const lp = [pos[0] - this.pos[0], pos[1] - this.pos[1]];
|
||||
for (const a of this.linkAreas) {
|
||||
if (lp[0] >= a.x && lp[0] <= a.x + a.width && lp[1] >= a.y && lp[1] <= a.y + a.height) {
|
||||
this.openLink(a.url);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
openLink(url) {
|
||||
try {
|
||||
if (!url.match(/^https?:\/\//) && !url.match(/^www\./)) {
|
||||
url = "https://" + url;
|
||||
}
|
||||
window.open(url, "_blank");
|
||||
} catch (err) {
|
||||
console.error("打开链接失败:", err);
|
||||
}
|
||||
}
|
||||
|
||||
onDblClick() {
|
||||
if (!this.isEditing) this.createTextEditor();
|
||||
}
|
||||
|
||||
onResize(size) {
|
||||
if (size && Array.isArray(size) && size.length >= 2) {
|
||||
this.size[0] = Math.max(size[0], 5);
|
||||
this.size[1] = Math.max(size[1], 5);
|
||||
app.graph.setDirtyCanvas(true);
|
||||
}
|
||||
}
|
||||
|
||||
getExtraMenuOptions(node, options) {
|
||||
options.unshift({
|
||||
content: "编辑文本",
|
||||
callback: () => this.createTextEditor()
|
||||
});
|
||||
options.push({
|
||||
content: "固定节点",
|
||||
callback: () => {
|
||||
this.flags.pinned = !this.flags.pinned;
|
||||
this.flags.allow_interaction = !this.flags.pinned;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onShowCustomPanelInfo(panel) {
|
||||
panel.querySelector('div.property[data-property="Mode"]')?.remove();
|
||||
panel.querySelector('div.property[data-property="Color"]')?.remove();
|
||||
}
|
||||
|
||||
onRemoved() {
|
||||
this.removeTextEditor();
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 静态属性与控件定义 ====================
|
||||
|
||||
TextEditorNode.type = "孤海注释";
|
||||
TextEditorNode.title = "孤海注释";
|
||||
TextEditorNode.title_mode = LiteGraph.NO_TITLE;
|
||||
TextEditorNode.collapsable = false;
|
||||
|
||||
TextEditorNode["@text"] = { type: "string", title: "文本内容", default: "双击编辑文本内容...", multiline: true };
|
||||
TextEditorNode["@fontSize"] = { type: "number", title: "字体大小", default: 24, min: 8, max: 200, step: 1 };
|
||||
TextEditorNode["@fontColor"] = { type: "color", title: "字体颜色", default: "#E3E3E3" };
|
||||
TextEditorNode["@backgroundColor"] = { type: "color", title: "背景颜色", default: "#1B4669" };
|
||||
TextEditorNode["@backgroundAlpha"] = { type: "number", title: "背景透明度", default: 0.6, min: 0, max: 1, step: 0.05 };
|
||||
TextEditorNode["@borderRadius"] = { type: "number", title: "圆角", default: 30, min: 0, max: 300, step: 1 };
|
||||
TextEditorNode["@padding"] = { type: "number", title: "内边距", default: 12, min: 0, max: 50, step: 1 };
|
||||
TextEditorNode["@lineHeight"] = { type: "number", title: "行距", default: 1.4, min: 0.8, max: 3, step: 0.1 };
|
||||
TextEditorNode["@textAlign"] = { type: "combo", title: "对齐方式", values: ["left", "center", "right"], default: "center" };
|
||||
|
||||
// ==================== 画布事件补丁 ====================
|
||||
|
||||
const _origDrawNode = LGraphCanvas.prototype.drawNode;
|
||||
LGraphCanvas.prototype.drawNode = function (node, ctx) {
|
||||
if (node.constructor === TextEditorNode) {
|
||||
node.bgcolor = "transparent";
|
||||
node.color = "#fff0";
|
||||
const result = _origDrawNode.apply(this, arguments);
|
||||
node.onDrawBackground(ctx);
|
||||
return result;
|
||||
}
|
||||
return _origDrawNode.apply(this, arguments);
|
||||
};
|
||||
|
||||
const _origPMDown = LGraphCanvas.prototype.processMouseDown;
|
||||
LGraphCanvas.prototype.processMouseDown = function (e) {
|
||||
if (!this.graph) return;
|
||||
const canvasPos = this.convertEventToCanvasOffset(e);
|
||||
const node = this.graph.getNodeOnPos(canvasPos[0], canvasPos[1], this.visible_nodes);
|
||||
if (node && node.constructor === TextEditorNode && !node.isEditing) {
|
||||
const lp = [canvasPos[0] - node.pos[0], canvasPos[1] - node.pos[1]];
|
||||
if (node.linkAreas && node.linkAreas.length > 0) {
|
||||
for (const a of node.linkAreas) {
|
||||
if (lp[0] >= a.x && lp[0] <= a.x + a.width &&
|
||||
lp[1] >= a.y && lp[1] <= a.y + a.height) {
|
||||
node.openLink(a.url);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return _origPMDown.call(this, e);
|
||||
};
|
||||
|
||||
// ==================== pinned 节点点击穿透 ====================
|
||||
|
||||
const mouseState = { processingMouseDown: false, lastMouseEvent: null };
|
||||
|
||||
const _origGNOP = LGraph.prototype.getNodeOnPos;
|
||||
LGraph.prototype.getNodeOnPos = function (x, y, nodes, margin) {
|
||||
if (nodes) {
|
||||
const recent = LiteGraph.getTime() -
|
||||
(LGraphCanvas.active_canvas && LGraphCanvas.active_canvas.last_mouseclick
|
||||
? LGraphCanvas.active_canvas.last_mouseclick : 0) < 300;
|
||||
if (mouseState.processingMouseDown && mouseState.lastMouseEvent &&
|
||||
mouseState.lastMouseEvent.type.includes("down") &&
|
||||
mouseState.lastMouseEvent.which === 1 && !recent) {
|
||||
nodes = [...nodes].filter(n => !(n instanceof TextEditorNode && n.flags.pinned));
|
||||
}
|
||||
}
|
||||
return _origGNOP.apply(this, [x, y, nodes, margin]);
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", function (e) {
|
||||
mouseState.processingMouseDown = true;
|
||||
mouseState.lastMouseEvent = e;
|
||||
}, true);
|
||||
|
||||
document.addEventListener("mouseup", function () {
|
||||
mouseState.processingMouseDown = false;
|
||||
}, true);
|
||||
|
||||
// ==================== 注册 ComfyUI 扩展 ====================
|
||||
|
||||
app.registerExtension({
|
||||
name: "孤海注释",
|
||||
registerCustomNodes() {
|
||||
TextEditorNode.setUp();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* COLOR Widget for ComfyUI
|
||||
*
|
||||
* This integration script is licensed under the GNU General Public License v3.0 (GPL-3.0).
|
||||
* If you incorporate or modify this code, please credit AILab as the original source:
|
||||
* https://github.com/1038lab
|
||||
*/
|
||||
|
||||
import { app } from "/scripts/app.js";
|
||||
|
||||
const getContrastTextColor = (hexColor) => {
|
||||
if (typeof hexColor !== 'string' || !/^#?[0-9a-fA-F]{6}$/.test(hexColor)) {
|
||||
return '#cccccc'; // fallback text color
|
||||
}
|
||||
|
||||
const hex = hexColor.replace('#', '');
|
||||
const r = parseInt(hex.substr(0, 2), 16);
|
||||
const g = parseInt(hex.substr(2, 2), 16);
|
||||
const b = parseInt(hex.substr(4, 2), 16);
|
||||
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||
|
||||
return luminance > 0.5 ? '#333333' : '#cccccc';
|
||||
};
|
||||
|
||||
const AILabColorWidget = {
|
||||
COLORCODE: (key, val) => {
|
||||
const widget = {};
|
||||
widget.y = 0;
|
||||
widget.name = key;
|
||||
widget.type = 'COLORCODE';
|
||||
widget.options = { default: '#222222' };
|
||||
widget.value = typeof val === 'string' ? val : '#222222';
|
||||
|
||||
widget.draw = function (ctx, node, widgetWidth, widgetY, height) {
|
||||
const hide = this.type !== 'COLORCODE' && app.canvas.ds.scale > 0.5;
|
||||
if (hide) {
|
||||
return;
|
||||
}
|
||||
|
||||
const margin = 15;
|
||||
const radius = 12;
|
||||
|
||||
ctx.fillStyle = this.value;
|
||||
ctx.beginPath();
|
||||
const x = margin;
|
||||
const y = widgetY;
|
||||
const w = widgetWidth - margin * 2;
|
||||
const h = height;
|
||||
ctx.moveTo(x + radius, y);
|
||||
ctx.lineTo(x + w - radius, y);
|
||||
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
|
||||
ctx.lineTo(x + w, y + h - radius);
|
||||
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
|
||||
ctx.lineTo(x + radius, y + h);
|
||||
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
|
||||
ctx.lineTo(x, y + radius);
|
||||
ctx.quadraticCurveTo(x, y, x + radius, y);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
ctx.strokeStyle = '#555';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = getContrastTextColor(this.value);
|
||||
ctx.font = '12px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
|
||||
const text = `${this.name} (${this.value})`;
|
||||
ctx.fillText(text, widgetWidth * 0.5, widgetY + height * 0.65);
|
||||
};
|
||||
|
||||
widget.mouse = function (e, pos, node) {
|
||||
if (e.type === 'pointerdown') {
|
||||
const margin = 15;
|
||||
|
||||
if (pos[0] >= margin && pos[0] <= node.size[0] - margin) {
|
||||
const picker = document.createElement('input');
|
||||
picker.type = 'color';
|
||||
picker.value = this.value;
|
||||
|
||||
picker.style.position = 'absolute';
|
||||
picker.style.left = '-9999px';
|
||||
picker.style.top = '-9999px';
|
||||
|
||||
document.body.appendChild(picker);
|
||||
|
||||
picker.addEventListener('change', () => {
|
||||
this.value = picker.value;
|
||||
node.graph._version++;
|
||||
node.setDirtyCanvas(true, true);
|
||||
picker.remove();
|
||||
});
|
||||
|
||||
picker.click();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
widget.computeSize = function (width) {
|
||||
return [width, 32];
|
||||
};
|
||||
|
||||
return widget;
|
||||
}
|
||||
};
|
||||
|
||||
app.registerExtension({
|
||||
name: "AILab.colorWidget",
|
||||
|
||||
getCustomWidgets() {
|
||||
return {
|
||||
COLORCODE: (node, inputName, inputData) => {
|
||||
return {
|
||||
widget: node.addCustomWidget(
|
||||
AILabColorWidget.COLORCODE(inputName, inputData?.[1]?.default || '#222222')
|
||||
),
|
||||
minWidth: 150,
|
||||
minHeight: 32,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,615 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
// ═══════════════════════════════════════════════
|
||||
// 孤海万能滑条 · Goohai Universal Slider
|
||||
// Canvas 绘制版:缩放到任意大小都始终可见
|
||||
// ═══════════════════════════════════════════════
|
||||
|
||||
|
||||
(function () {
|
||||
const ID = "goohai-us-css";
|
||||
if (document.getElementById(ID)) return;
|
||||
const s = document.createElement("style");
|
||||
s.id = ID;
|
||||
s.textContent = `
|
||||
.ghs-overlay{position:fixed;inset:0;background:rgba(0,0,0,.55);backdrop-filter:blur(3px);z-index:100000;display:flex;justify-content:center;align-items:center;animation:ghsIn .15s ease}
|
||||
@keyframes ghsIn{from{opacity:0}to{opacity:1}}
|
||||
@keyframes ghsPop{from{opacity:0;transform:translateY(-8px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}
|
||||
.ghs-panel{background:#1c1c1e;border:1px solid #333;border-radius:14px;padding:28px 32px;min-width:380px;box-shadow:0 24px 80px rgba(0,0,0,.6);animation:ghsPop .2s ease;font-family:'Segoe UI',system-ui,-apple-system,sans-serif;--gs-c:#e8c547}
|
||||
.ghs-ptitle{font-size:16px;font-weight:700;color:#eee;margin-bottom:22px}
|
||||
.ghs-row{display:flex;align-items:center;margin-bottom:14px}
|
||||
.ghs-rlbl{width:72px;font-size:12.5px;color:#999;flex-shrink:0}
|
||||
.ghs-inp{flex:1;background:#2a2a2c;border:1px solid #3a3a3c;border-radius:8px;padding:8px 12px;color:#eee;font-size:13px;outline:none;transition:border-color .2s;font-family:inherit}
|
||||
.ghs-inp:focus{border-color:var(--gs-c)}
|
||||
.ghs-clr{width:48px;height:34px;padding:2px;border-radius:8px;border:1px solid #3a3a3c;background:#2a2a2c;cursor:pointer}
|
||||
.ghs-btns{display:flex;justify-content:flex-end;gap:10px;margin-top:22px}
|
||||
.ghs-btn{padding:8px 22px;border-radius:8px;border:none;cursor:pointer;font-size:13px;font-weight:500;transition:all .15s;font-family:inherit}
|
||||
.ghs-bx{background:#2a2a2c;color:#aaa;border:1px solid #3a3a3c}
|
||||
.ghs-bx:hover{background:#333;color:#ccc}
|
||||
.ghs-bok{background:var(--gs-c);color:#111;font-weight:600}
|
||||
.ghs-bok:hover{filter:brightness(1.12)}
|
||||
.ghs-radio-wrap{flex:1;display:flex;gap:20px;align-items:center}
|
||||
.ghs-radio-label{display:flex;align-items:center;gap:6px;cursor:pointer;color:#eee;font-size:13px;padding:6px 12px;border-radius:6px;background:#2a2a2c;border:1px solid #3a3a3c;transition:all .15s}
|
||||
.ghs-radio-label:hover{border-color:var(--gs-c)}
|
||||
.ghs-radio-label input[type="radio"]{appearance:none;-webkit-appearance:none;width:16px;height:16px;border:2px solid #555;border-radius:50%;cursor:pointer;transition:all .15s;position:relative}
|
||||
.ghs-radio-label input[type="radio"]:checked{border-color:var(--gs-c)}
|
||||
.ghs-radio-label input[type="radio"]:checked::after{content:'';position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:8px;height:8px;border-radius:50%;background:var(--gs-c)}
|
||||
`;
|
||||
document.head.appendChild(s);
|
||||
})();
|
||||
|
||||
// ── 工具函数 ──────────────────────────────────
|
||||
const pct = (v, mn, mx) => { const r = mx - mn; return r > 0 ? ((v - mn) / r) * 100 : 0; };
|
||||
const clamp = (v, mn, mx) => Math.max(mn, Math.min(mx, v));
|
||||
const snap = (v, mn, step) => step > 0 ? Math.round((v - mn) / step) * step + mn : v;
|
||||
const fmt = (v, isInt) => isInt ? String(Math.round(v)) : v.toFixed(2);
|
||||
function castVal(v, isInt) {
|
||||
if (isInt) return parseInt(Math.round(v), 10);
|
||||
return parseFloat(v.toFixed(2));
|
||||
}
|
||||
|
||||
// ── 统一的值计算函数,先 snap 再按类型取整 ──
|
||||
function calcValue(v, mn, mx, step, isInt) {
|
||||
v = snap(v, mn, step);
|
||||
v = clamp(v, mn, mx);
|
||||
return castVal(v, isInt);
|
||||
}
|
||||
|
||||
// ── Canvas 圆角矩形 ──────────────────────────
|
||||
function rrect(ctx, x, y, w, h, r) {
|
||||
if (w < 0) w = 0;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||
ctx.arcTo(x, y + h, x, y, r);
|
||||
ctx.arcTo(x, y, x + w, y, r);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
// ── updateVis ────────────────────────────────
|
||||
function updateVis(n) {
|
||||
n.setDirtyCanvas(true, true);
|
||||
}
|
||||
|
||||
// ── syncWidgetType ───────────────────────────
|
||||
function syncWidgetType(node) {
|
||||
const g = node._gs;
|
||||
if (!g || !g.widget) return;
|
||||
const p = node.properties;
|
||||
const isInt = p.sliderType === "int";
|
||||
g.widget.type = isInt ? "INT" : "FLOAT";
|
||||
let v = g.widget.value;
|
||||
v = clamp(v, p.sliderMin, p.sliderMax);
|
||||
v = isInt ? Math.round(v) : parseFloat(v.toFixed(2));
|
||||
g.widget.value = v;
|
||||
}
|
||||
|
||||
// ── syncOutputType ───────────────────────────
|
||||
function syncOutputType(node) {
|
||||
const g = node._gs;
|
||||
if (!g || !g.outputTypeWidget) return;
|
||||
const isInt = node.properties.sliderType === "int";
|
||||
g.outputTypeWidget.value = isInt ? "int" : "float";
|
||||
}
|
||||
|
||||
// ── 清理拖拽状态 ─────────────────────────────
|
||||
function cleanupDrag(node) {
|
||||
const g = node._gs;
|
||||
if (!g) return;
|
||||
g._dragging = false;
|
||||
if (g._docCleanup) {
|
||||
g._docCleanup();
|
||||
g._docCleanup = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── showSettings ─────────────────────────────
|
||||
function showSettings(node) {
|
||||
cleanupDrag(node);
|
||||
document.querySelectorAll(".ghs-overlay").forEach((e) => e.remove());
|
||||
const p = node.properties;
|
||||
|
||||
const ov = document.createElement("div");
|
||||
ov.className = "ghs-overlay";
|
||||
ov.setAttribute("tabindex", "-1");
|
||||
|
||||
const pl = document.createElement("div");
|
||||
pl.className = "ghs-panel";
|
||||
pl.style.setProperty("--gs-c", p.sliderColor);
|
||||
|
||||
const title = document.createElement("div");
|
||||
title.className = "ghs-ptitle";
|
||||
title.textContent = "🎮 孤海滑条 设置";
|
||||
pl.appendChild(title);
|
||||
|
||||
function addRow(labelText, el) {
|
||||
const r = document.createElement("div");
|
||||
r.className = "ghs-row";
|
||||
const l = document.createElement("label");
|
||||
l.className = "ghs-rlbl";
|
||||
l.textContent = labelText;
|
||||
r.append(l, el);
|
||||
pl.appendChild(r);
|
||||
}
|
||||
function mkInp(type, value, attrs) {
|
||||
const i = document.createElement("input");
|
||||
i.className = "ghs-inp";
|
||||
i.type = type;
|
||||
i.value = value;
|
||||
if (attrs) Object.entries(attrs).forEach(([k, v]) => i.setAttribute(k, v));
|
||||
return i;
|
||||
}
|
||||
|
||||
const clrI = document.createElement("input");
|
||||
clrI.className = "ghs-clr";
|
||||
clrI.type = "color";
|
||||
clrI.value = p.sliderColor;
|
||||
addRow("滑条颜色", clrI);
|
||||
|
||||
const radioWrap = document.createElement("div");
|
||||
radioWrap.className = "ghs-radio-wrap";
|
||||
const types = [
|
||||
{ v: "float", t: "浮点 (Float)" },
|
||||
{ v: "int", t: "整数 (Integer)" },
|
||||
];
|
||||
let selectedType = p.sliderType;
|
||||
types.forEach((opt) => {
|
||||
const label = document.createElement("label");
|
||||
label.className = "ghs-radio-label";
|
||||
const radio = document.createElement("input");
|
||||
radio.type = "radio";
|
||||
radio.name = "ghs-slider-type";
|
||||
radio.value = opt.v;
|
||||
radio.checked = (p.sliderType === opt.v);
|
||||
radio.addEventListener("change", () => { if (radio.checked) selectedType = opt.v; });
|
||||
label.append(radio, document.createTextNode(opt.t));
|
||||
radioWrap.appendChild(label);
|
||||
});
|
||||
addRow("类型", radioWrap);
|
||||
|
||||
const minI = mkInp("number", p.sliderMin, { step: "any" });
|
||||
addRow("最小值", minI);
|
||||
const maxI = mkInp("number", p.sliderMax, { step: "any" });
|
||||
addRow("最大值", maxI);
|
||||
const stepI = mkInp("number", p.sliderStep, { step: "any", min: "0.0001" });
|
||||
addRow("步长", stepI);
|
||||
const lblI = mkInp("text", p.sliderLabel);
|
||||
addRow("显示名称", lblI);
|
||||
|
||||
const btns = document.createElement("div");
|
||||
btns.className = "ghs-btns";
|
||||
const bCancel = document.createElement("button");
|
||||
bCancel.className = "ghs-btn ghs-bx";
|
||||
bCancel.textContent = "取消";
|
||||
bCancel.onclick = () => ov.remove();
|
||||
const bOk = document.createElement("button");
|
||||
bOk.className = "ghs-btn ghs-bok";
|
||||
bOk.textContent = "确定";
|
||||
bOk.onclick = () => {
|
||||
let type = selectedType;
|
||||
let mn = parseFloat(minI.value);
|
||||
let mx = parseFloat(maxI.value);
|
||||
let step = parseFloat(stepI.value);
|
||||
let label = (lblI.value || "").trim() || "值";
|
||||
let color = clrI.value;
|
||||
|
||||
if (isNaN(mn)) mn = 0;
|
||||
if (isNaN(mx)) mx = 1;
|
||||
if (mn > mx) { const t = mn; mn = mx; mx = t; }
|
||||
if (isNaN(step) || step <= 0) step = type === "int" ? 1 : 0.01;
|
||||
if (type === "int") {
|
||||
mn = Math.round(mn);
|
||||
mx = Math.round(mx);
|
||||
step = Math.max(1, Math.round(step));
|
||||
}
|
||||
|
||||
p.sliderType = type;
|
||||
p.sliderMin = mn;
|
||||
p.sliderMax = mx;
|
||||
p.sliderStep = step;
|
||||
p.sliderLabel = label;
|
||||
p.sliderColor = color;
|
||||
|
||||
const w = node._gs.widget;
|
||||
if (w) {
|
||||
w.value = calcValue(w.value, mn, mx, step, type === "int");
|
||||
}
|
||||
|
||||
syncWidgetType(node);
|
||||
syncOutputType(node);
|
||||
updateVis(node);
|
||||
node.setDirtyCanvas(true, true);
|
||||
ov.remove();
|
||||
};
|
||||
|
||||
btns.append(bCancel, bOk);
|
||||
pl.appendChild(btns);
|
||||
ov.appendChild(pl);
|
||||
|
||||
ov.addEventListener("click", (e) => { if (e.target === ov) ov.remove(); });
|
||||
ov.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") ov.remove();
|
||||
if (e.key === "Enter") bOk.click();
|
||||
});
|
||||
|
||||
document.body.appendChild(ov);
|
||||
ov.focus();
|
||||
}
|
||||
|
||||
// ── setupSlider ──────────────────────────────
|
||||
function setupSlider(node) {
|
||||
const D = {
|
||||
sliderType: "float", sliderMin: 0, sliderMax: 1,
|
||||
sliderStep: 0.01, sliderLabel: "值", sliderColor: "#e8c547",
|
||||
};
|
||||
if (!node.properties) node.properties = {};
|
||||
for (const [k, v] of Object.entries(D)) {
|
||||
if (node.properties[k] === undefined) node.properties[k] = v;
|
||||
}
|
||||
const p = node.properties;
|
||||
const isInt = p.sliderType === "int";
|
||||
|
||||
/* 隐藏 PY 自带滑条 */
|
||||
const dw = node.widgets ? node.widgets.find((w) => w.name === "值") : null;
|
||||
if (dw) {
|
||||
dw.hidden = true;
|
||||
dw.computeSize = () => [0, 0];
|
||||
}
|
||||
|
||||
/* output_type 隐藏 widget */
|
||||
let outputTypeWidget = node.widgets
|
||||
? node.widgets.find((w) => w.name === "output_type")
|
||||
: null;
|
||||
if (!outputTypeWidget) {
|
||||
node.addWidget("combo", "output_type", isInt ? "int" : "float", function () {}, { values: ["float", "int"] });
|
||||
outputTypeWidget = node.widgets ? node.widgets.find((w) => w.name === "output_type") : null;
|
||||
}
|
||||
if (outputTypeWidget) {
|
||||
outputTypeWidget.value = isInt ? "int" : "float";
|
||||
outputTypeWidget.type = "hidden";
|
||||
outputTypeWidget.hidden = true;
|
||||
outputTypeWidget.computeSize = () => [0, 0];
|
||||
outputTypeWidget.draw = function () {};
|
||||
outputTypeWidget.mouse = function () {};
|
||||
}
|
||||
|
||||
/* 节点外观 */
|
||||
node.color = "#2D384D";
|
||||
node.bgcolor = "#2D384D";
|
||||
|
||||
/* 覆盖标题渲染 */
|
||||
const origFG = node.onDrawForeground;
|
||||
node.onDrawForeground = function (ctx) {
|
||||
const th = (typeof LiteGraph !== "undefined" && LiteGraph.NODE_TITLE_HEIGHT) || 30;
|
||||
const r = (typeof LiteGraph !== "undefined" && LiteGraph.NODE_ROUND_RADIUS) || 8;
|
||||
const w = this.size[0];
|
||||
const x = 0, y = -th, fw = w, fh = th + 2;
|
||||
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.lineTo(x + fw - r, y);
|
||||
ctx.arcTo(x + fw, y, x + fw, y + r, r);
|
||||
ctx.lineTo(x + fw, y + fh);
|
||||
ctx.lineTo(x, y + fh);
|
||||
ctx.lineTo(x, y + r);
|
||||
ctx.arcTo(x, y, x + r, y, r);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = this.color || "#2D384D";
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
ctx.save();
|
||||
ctx.font = "20px 'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif";
|
||||
ctx.fillStyle = "#E3E3E3";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "top";
|
||||
ctx.fillText(this.title || "", w / 2, -th + 10);
|
||||
ctx.restore();
|
||||
if (origFG) origFG.call(this, ctx);
|
||||
};
|
||||
|
||||
/* ── 绘制状态缓存 ── */
|
||||
const ds = { trackLeft: 14, trackW: 192 };
|
||||
|
||||
node._gs = {
|
||||
widget: dw,
|
||||
outputTypeWidget: outputTypeWidget,
|
||||
_dragging: false,
|
||||
_docCleanup: null,
|
||||
};
|
||||
|
||||
syncWidgetType(node);
|
||||
syncOutputType(node);
|
||||
|
||||
/* ══════════════════════════════════════════
|
||||
* 注册 Canvas 自定义 Widget
|
||||
* ══════════════════════════════════════════ */
|
||||
node.addCustomWidget({
|
||||
name: "ghs_ui",
|
||||
type: "goohai_slider",
|
||||
|
||||
draw(ctx, node, W, y, H) {
|
||||
const g = node._gs;
|
||||
if (!g) return;
|
||||
const p = node.properties;
|
||||
const v = g.widget ? g.widget.value : 0;
|
||||
const isInt = p.sliderType === "int";
|
||||
const ratio = clamp(pct(v, p.sliderMin, p.sliderMax), 0, 100);
|
||||
const color = p.sliderColor;
|
||||
|
||||
|
||||
const ml = 14;
|
||||
const mr = 24;
|
||||
ds.trackLeft = ml;
|
||||
ds.trackW = W - ml - mr;
|
||||
|
||||
/* ── 居中标签(名称 16px + 数值 20px bold) ── */
|
||||
ctx.save();
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.textAlign = "left";
|
||||
|
||||
const nameFont = "16px 'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif";
|
||||
const valFont = "bold 24px 'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif";
|
||||
|
||||
ctx.font = nameFont;
|
||||
const nameText = p.sliderLabel;
|
||||
const nameW = ctx.measureText(nameText).width;
|
||||
|
||||
ctx.font = valFont;
|
||||
const valText = " " + fmt(v, isInt);
|
||||
const valW = ctx.measureText(valText).width;
|
||||
|
||||
const lx = (W - nameW - valW) / 2;
|
||||
const ly = y + 6;
|
||||
|
||||
ctx.shadowColor = "rgba(0,0,0,0.6)";
|
||||
ctx.shadowBlur = 3;
|
||||
ctx.shadowOffsetY = 1;
|
||||
|
||||
ctx.font = nameFont;
|
||||
ctx.fillStyle = "#B2B7BD";
|
||||
ctx.fillText(nameText, lx, ly);
|
||||
|
||||
ctx.font = valFont;
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillText(valText, lx + nameW, ly);
|
||||
ctx.restore();
|
||||
|
||||
/* ── 轨道背景(10px 高,圆角 5) */
|
||||
const trackY = y + 34;
|
||||
const trackH = 10;
|
||||
const trackR = 5;
|
||||
|
||||
ctx.save();
|
||||
ctx.shadowColor = "rgba(0,0,0,0.5)";
|
||||
ctx.shadowBlur = 2;
|
||||
ctx.shadowOffsetY = 1;
|
||||
rrect(ctx, ml, trackY, ds.trackW, trackH, trackR);
|
||||
ctx.fillStyle = "#1a1a1a";
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
const fillW = ds.trackW * ratio / 100;
|
||||
|
||||
/* ── 发光层 ── */
|
||||
if (fillW > 0) {
|
||||
ctx.save();
|
||||
ctx.globalAlpha = 0.2;
|
||||
ctx.shadowColor = color;
|
||||
ctx.shadowBlur = 10;
|
||||
rrect(ctx, ml, trackY + 2, fillW, trackH - 4, 5);
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/* ── 填充条 ── */
|
||||
if (fillW > 0) {
|
||||
ctx.save();
|
||||
rrect(ctx, ml, trackY, fillW, trackH, trackR);
|
||||
ctx.fillStyle = color;
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/* ── 圆形旋钮(16px 直径) ── */
|
||||
const thumbX = ml + fillW;
|
||||
const thumbY = trackY + trackH / 2;
|
||||
const thumbR = 8;
|
||||
|
||||
ctx.save();
|
||||
if (g._dragging) {
|
||||
ctx.shadowColor = "rgba(232,197,71,0.12)";
|
||||
ctx.shadowBlur = 5;
|
||||
} else {
|
||||
ctx.shadowColor = "rgba(0,0,0,0.4)";
|
||||
ctx.shadowBlur = 4;
|
||||
}
|
||||
ctx.fillStyle = "#f5f0e8";
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(thumbX, thumbY, thumbR, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
},
|
||||
|
||||
mouse(event, pos, node) {
|
||||
const g = node._gs;
|
||||
if (!g) return;
|
||||
const p = node.properties;
|
||||
|
||||
/* ── mouseup / pointerup:结束拖拽 ── */
|
||||
if (event.type === "mouseup" || event.type === "pointerup") {
|
||||
if (g._dragging) {
|
||||
g._dragging = false;
|
||||
if (g._docCleanup) { g._docCleanup(); g._docCleanup = null; }
|
||||
node.setDirtyCanvas(true, true);
|
||||
return true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
/* ── mousemove / pointermove:拖拽中实时更新 ── */
|
||||
if ((event.type === "mousemove" || event.type === "pointermove") && g._dragging) {
|
||||
const isInt = p.sliderType === "int";
|
||||
const ratio = clamp((pos[0] - ds.trackLeft) / ds.trackW, 0, 1);
|
||||
let v = p.sliderMin + ratio * (p.sliderMax - p.sliderMin);
|
||||
v = calcValue(v, p.sliderMin, p.sliderMax, p.sliderStep, isInt);
|
||||
if (g.widget) g.widget.value = v;
|
||||
node.setDirtyCanvas(true, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ── 仅处理左键 mousedown / pointerdown ── */
|
||||
if (event.type !== "mousedown" && event.type !== "pointerdown") return;
|
||||
if (event.button !== 0) return;
|
||||
|
||||
/* ── 清理可能残留的拖拽状态 ── */
|
||||
if (g._dragging) {
|
||||
g._dragging = false;
|
||||
if (g._docCleanup) { g._docCleanup(); g._docCleanup = null; }
|
||||
}
|
||||
|
||||
/* ── 左键:跳到点击位置并开始拖拽 ── */
|
||||
const isInt = p.sliderType === "int";
|
||||
const ratio = clamp((pos[0] - ds.trackLeft) / ds.trackW, 0, 1);
|
||||
let v = p.sliderMin + ratio * (p.sliderMax - p.sliderMin);
|
||||
v = calcValue(v, p.sliderMin, p.sliderMax, p.sliderStep, isInt);
|
||||
|
||||
if (g.widget) g.widget.value = v;
|
||||
node.setDirtyCanvas(true, false);
|
||||
|
||||
g._dragging = true;
|
||||
|
||||
/* ── document 备用监听(防止 LiteGraph 不转发后续事件时的保底) ── */
|
||||
const startCX = event.clientX;
|
||||
const startVal = v;
|
||||
|
||||
function onDocMove(e2) {
|
||||
if (!g._dragging) return;
|
||||
const dx = e2.clientX - startCX;
|
||||
const scale = app.canvas.ds.scale || 1;
|
||||
const graphDx = dx / scale;
|
||||
const ratioD = graphDx / ds.trackW;
|
||||
const valDelta = ratioD * (p.sliderMax - p.sliderMin);
|
||||
let nv = startVal + valDelta;
|
||||
nv = calcValue(nv, p.sliderMin, p.sliderMax, p.sliderStep, isInt);
|
||||
if (g.widget) g.widget.value = nv;
|
||||
node.setDirtyCanvas(true, false);
|
||||
}
|
||||
|
||||
function onDocUp() {
|
||||
if (!g._dragging) return;
|
||||
g._dragging = false;
|
||||
g._docCleanup = null;
|
||||
document.removeEventListener("mousemove", onDocMove);
|
||||
document.removeEventListener("mouseup", onDocUp);
|
||||
node.setDirtyCanvas(true, true);
|
||||
}
|
||||
|
||||
g._docCleanup = function () {
|
||||
document.removeEventListener("mousemove", onDocMove);
|
||||
document.removeEventListener("mouseup", onDocUp);
|
||||
};
|
||||
document.addEventListener("mousemove", onDocMove);
|
||||
document.addEventListener("mouseup", onDocUp);
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
computeSize(width) {
|
||||
return [width, 60];
|
||||
},
|
||||
});
|
||||
|
||||
/* 监听外部值变化 */
|
||||
const origCB = node.onWidgetChanged;
|
||||
node.onWidgetChanged = function (name, value, widget) {
|
||||
if (origCB) origCB.call(this, name, value, widget);
|
||||
if (name === "值") updateVis(this);
|
||||
};
|
||||
|
||||
/* 节点宽度 */
|
||||
node.size[0] = Math.max(node.size[0], 300);
|
||||
}
|
||||
|
||||
// ── 注册扩展 ────────────────────────────────
|
||||
app.registerExtension({
|
||||
name: "goohai.universal.slider",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "GoohaiUniversalSlider") return;
|
||||
|
||||
/* ── 圆角标题补丁 ── */
|
||||
if (
|
||||
typeof LGraphCanvas !== "undefined" &&
|
||||
LGraphCanvas.prototype.drawNode &&
|
||||
typeof LiteGraph !== "undefined" &&
|
||||
!LGraphCanvas.prototype._ghsRadiusPatched
|
||||
) {
|
||||
LGraphCanvas.prototype._ghsRadiusPatched = true;
|
||||
const origDrawNode = LGraphCanvas.prototype.drawNode;
|
||||
LGraphCanvas.prototype.drawNode = function (node, ctx, ...args) {
|
||||
if (node.type === "GoohaiUniversalSlider") {
|
||||
const origR = LiteGraph.NODE_ROUND_RADIUS;
|
||||
LiteGraph.NODE_ROUND_RADIUS = 8;
|
||||
origDrawNode.call(this, node, ctx, ...args);
|
||||
LiteGraph.NODE_ROUND_RADIUS = origR;
|
||||
} else {
|
||||
origDrawNode.call(this, node, ctx, ...args);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/* ── onNodeCreated ── */
|
||||
const onCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onCreated ? onCreated.apply(this, arguments) : undefined;
|
||||
setupSlider(this);
|
||||
return r;
|
||||
};
|
||||
|
||||
/* ── configure(加载已保存的节点时恢复状态) ── */
|
||||
const onConfigure = nodeType.prototype.configure;
|
||||
nodeType.prototype.configure = function (info) {
|
||||
if (onConfigure) onConfigure.apply(this, arguments);
|
||||
if (!this._gs) return;
|
||||
const p = this.properties;
|
||||
|
||||
|
||||
const w = this._gs.widget;
|
||||
if (w) {
|
||||
const isInt = p.sliderType === "int";
|
||||
w.value = calcValue(w.value, p.sliderMin, p.sliderMax, p.sliderStep, isInt);
|
||||
}
|
||||
|
||||
syncWidgetType(this);
|
||||
syncOutputType(this);
|
||||
updateVis(this);
|
||||
};
|
||||
|
||||
/* ── 右键上下文菜单 ── */
|
||||
const origExtra = nodeType.prototype.getExtraMenuOptions;
|
||||
nodeType.prototype.getExtraMenuOptions = function (canvas, options) {
|
||||
let r;
|
||||
try {
|
||||
if (typeof origExtra === "function") {
|
||||
r = origExtra.apply(this, arguments);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[GoohaiSlider] getExtraMenuOptions:", e);
|
||||
}
|
||||
if (Array.isArray(options)) {
|
||||
options.splice(0, 0, null, {
|
||||
content: "🎮 孤海滑条 设置",
|
||||
callback: () => showSettings(this),
|
||||
});
|
||||
}
|
||||
return r;
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,755 @@
|
||||
// custom_nodes/GoohaiTools-comfyui/web/js/id_photo_clothing.js
|
||||
// 证件照服装选择_孤海 —— 前端 UI 扩展
|
||||
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
const NODE_NAME = "IDPhotoClothingSelector_孤海";
|
||||
const THUMB_W = 128;
|
||||
const THUMB_H = 180;
|
||||
const GAP = 5;
|
||||
const BORDER_RADIUS = 10;
|
||||
const COLS = 4;
|
||||
const SCROLLBAR_EXTRA = 10;
|
||||
const GALLERY_WIDTH = COLS * THUMB_W + (COLS - 1) * GAP + SCROLLBAR_EXTRA;
|
||||
const BORDER_HIGHLIGHT = 3;
|
||||
const SEARCH_AREA_H = 34;
|
||||
const INNER_GAP = 6;
|
||||
const PROMPT_TEXTAREA_H = THUMB_H - INNER_GAP - SEARCH_AREA_H;
|
||||
const TOP_ROW_GAP = 15;
|
||||
const BOTTOM_PAD = 20;
|
||||
|
||||
let _dataCache = null;
|
||||
|
||||
async function loadTemplateData() {
|
||||
if (_dataCache) return _dataCache;
|
||||
try {
|
||||
const resp = await fetch("/goohai/id_photo_templates");
|
||||
_dataCache = await resp.json();
|
||||
} catch (e) {
|
||||
console.error("[GoohaiTools] 加载模板数据失败:", e);
|
||||
_dataCache = { categories: [], templates: {} };
|
||||
}
|
||||
return _dataCache;
|
||||
}
|
||||
|
||||
// ==================== UI 辅助元素 ====================
|
||||
|
||||
function createCheckmark() {
|
||||
const el = document.createElement("div");
|
||||
el.textContent = "✓";
|
||||
Object.assign(el.style, {
|
||||
position: "absolute", top: "2px", right: "2px",
|
||||
width: "18px", height: "18px",
|
||||
background: "#4CAF50", borderRadius: "50%",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
color: "#fff", fontSize: "13px", fontWeight: "bold",
|
||||
zIndex: "10", pointerEvents: "none",
|
||||
boxShadow: "0 1px 4px rgba(0,0,0,0.4)",
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
function createSelectedBadge() {
|
||||
const el = document.createElement("div");
|
||||
el.textContent = "已选";
|
||||
Object.assign(el.style, {
|
||||
position: "absolute", top: "4px", left: "4px",
|
||||
padding: "2px 6px",
|
||||
background: "#4CAF50",
|
||||
borderRadius: "4px",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
color: "#fff", fontSize: "10px", fontWeight: "bold",
|
||||
zIndex: "10", pointerEvents: "none",
|
||||
boxShadow: "0 1px 4px rgba(0,0,0,0.4)",
|
||||
whiteSpace: "nowrap",
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
function createImageFallback(parent, title, width, height, borderRadius) {
|
||||
const fb = document.createElement("div");
|
||||
Object.assign(fb.style, {
|
||||
width, height,
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
background: "#333", color: "#999", fontSize: "11px",
|
||||
padding: "4px", textAlign: "center", borderRadius,
|
||||
});
|
||||
fb.textContent = title;
|
||||
parent.appendChild(fb);
|
||||
}
|
||||
|
||||
// ==================== 注册扩展 ====================
|
||||
|
||||
app.registerExtension({
|
||||
name: "goohai.id_photo_clothing",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== NODE_NAME) return;
|
||||
|
||||
const origOnCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
origOnCreated?.apply(this, arguments);
|
||||
this.color = "#3a4d64";
|
||||
this.bgcolor = "#2c3849";
|
||||
this._initClothingUI();
|
||||
};
|
||||
|
||||
nodeType.prototype._initClothingUI = async function () {
|
||||
const node = this;
|
||||
const data = await loadTemplateData();
|
||||
|
||||
const allTemplates = data.templates;
|
||||
const allCategories = data.categories;
|
||||
|
||||
// ========== 状态变量 ==========
|
||||
const defaultCat = allCategories[0] || "";
|
||||
let currentCategory = defaultCat;
|
||||
let searchQuery = "";
|
||||
let isSearching = false;
|
||||
let selectedCategory = "";
|
||||
let selectedFilename = "";
|
||||
let selectedPrompt = "";
|
||||
let _lastSyncedValue = "";
|
||||
let _lastAppliedMaxH = 0;
|
||||
|
||||
// ========== 提示词输出 widget ==========
|
||||
const promptWidget = node.widgets?.find(w => w.name === "提示词输出");
|
||||
if (promptWidget) {
|
||||
_lastSyncedValue = promptWidget.value || "";
|
||||
}
|
||||
|
||||
// ========== 挂接「风格类型」下拉回调 ==========
|
||||
const catWidget = node.widgets?.find(w => w.name === "风格类型");
|
||||
if (catWidget) {
|
||||
const origCb = catWidget.callback;
|
||||
catWidget.callback = function (v) {
|
||||
origCb?.call(this, v);
|
||||
currentCategory = v;
|
||||
searchQuery = "";
|
||||
isSearching = false;
|
||||
searchInput.value = "";
|
||||
clearBtn.style.display = "none";
|
||||
renderGallery();
|
||||
};
|
||||
}
|
||||
|
||||
// ========== 辅助函数 ==========
|
||||
|
||||
function syncPrompt() {
|
||||
if (promptWidget) {
|
||||
promptWidget.value = selectedPrompt;
|
||||
const el = promptWidget.element;
|
||||
if (el) {
|
||||
const ta = el.tagName === "TEXTAREA" ? el : el.querySelector?.("textarea");
|
||||
if (ta) ta.value = selectedPrompt;
|
||||
}
|
||||
}
|
||||
promptArea.value = selectedPrompt;
|
||||
_lastSyncedValue = selectedPrompt;
|
||||
}
|
||||
|
||||
function findTemplate(cat, fname) {
|
||||
return (allTemplates[cat] || []).find(t => t.filename === fname);
|
||||
}
|
||||
|
||||
function saveSelectionState() {
|
||||
if (!node.properties) node.properties = {};
|
||||
const actualPrompt = promptWidget ? (promptWidget.value || "") : selectedPrompt;
|
||||
if (selectedFilename && selectedCategory) {
|
||||
node.properties._goohai_sel = {
|
||||
cat: selectedCategory,
|
||||
file: selectedFilename,
|
||||
curCat: currentCategory,
|
||||
prompt: actualPrompt,
|
||||
};
|
||||
} else {
|
||||
node.properties._goohai_sel = {
|
||||
_none: true,
|
||||
curCat: currentCategory,
|
||||
prompt: actualPrompt,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function deselectAll() {
|
||||
selectedCategory = "";
|
||||
selectedFilename = "";
|
||||
selectedPrompt = "";
|
||||
syncPrompt();
|
||||
saveSelectionState();
|
||||
renderGallery();
|
||||
}
|
||||
|
||||
function selectTemplate(tpl) {
|
||||
selectedCategory = tpl.category;
|
||||
selectedFilename = tpl.filename;
|
||||
selectedPrompt = tpl.prompt || "";
|
||||
syncPrompt();
|
||||
saveSelectionState();
|
||||
renderGallery();
|
||||
}
|
||||
|
||||
function buildDisplayList() {
|
||||
let pool = [];
|
||||
if (isSearching) {
|
||||
const keywords = searchQuery
|
||||
.toLowerCase()
|
||||
.split(/[,,、\s;;\-_.!@#$%^&*()+=${}|\\:"'<>?\/~`]+/)
|
||||
.filter(k => k.length > 0);
|
||||
|
||||
for (const cat of allCategories) {
|
||||
for (const tpl of (allTemplates[cat] || [])) {
|
||||
const catLower = cat.toLowerCase();
|
||||
const titleLower = tpl.title.toLowerCase();
|
||||
const promptLower = tpl.prompt.toLowerCase();
|
||||
const allMatch = keywords.every(kw =>
|
||||
catLower.includes(kw)
|
||||
|| titleLower.includes(kw)
|
||||
|| promptLower.includes(kw)
|
||||
);
|
||||
if (allMatch) {
|
||||
pool.push(tpl);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pool = (allTemplates[currentCategory] || []).slice();
|
||||
}
|
||||
|
||||
const list = [];
|
||||
const sel = selectedFilename && selectedCategory
|
||||
? findTemplate(selectedCategory, selectedFilename)
|
||||
: null;
|
||||
|
||||
list.push(sel
|
||||
? { _kind: "first_preview", ...sel, _isSel: false, _isFirst: true }
|
||||
: { _kind: "none", title: "无", prompt: "", _isSel: false, _isFirst: true }
|
||||
);
|
||||
|
||||
for (const tpl of pool) {
|
||||
const isSelected = !!sel
|
||||
&& tpl.category === selectedCategory
|
||||
&& tpl.filename === selectedFilename;
|
||||
list.push({ _kind: "item", ...tpl, _isSel: isSelected, _isFirst: false });
|
||||
}
|
||||
|
||||
return { items: list, poolCount: pool.length };
|
||||
}
|
||||
|
||||
// ==================== DOM 构建 ====================
|
||||
|
||||
const container = document.createElement("div");
|
||||
Object.assign(container.style, {
|
||||
width: "100%",
|
||||
boxSizing: "border-box",
|
||||
fontFamily: "'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif",
|
||||
padding: "0px 4px 4px 4px",
|
||||
});
|
||||
|
||||
// ========== 顶部横排区域:预览框(左) + 提示词/搜索(右) ==========
|
||||
|
||||
const topRow = document.createElement("div");
|
||||
Object.assign(topRow.style, {
|
||||
display: "flex",
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
width: "100%",
|
||||
gap: `${TOP_ROW_GAP}px`,
|
||||
marginBottom: "6px",
|
||||
});
|
||||
|
||||
// ---- 左侧预览框 ----
|
||||
const previewBox = document.createElement("div");
|
||||
Object.assign(previewBox.style, {
|
||||
width: `${THUMB_W}px`,
|
||||
height: `${THUMB_H}px`,
|
||||
minWidth: `${THUMB_W}px`,
|
||||
boxSizing: "border-box",
|
||||
border: `${BORDER_HIGHLIGHT}px solid #4CAF50`,
|
||||
borderRadius: `${BORDER_RADIUS}px`,
|
||||
overflow: "hidden",
|
||||
position: "relative",
|
||||
cursor: "pointer",
|
||||
flexShrink: "0",
|
||||
transition: "transform .1s",
|
||||
background: "#1e1e1e",
|
||||
});
|
||||
previewBox.addEventListener("mouseenter", () => {
|
||||
previewBox.style.transform = "scale(1.03)";
|
||||
});
|
||||
previewBox.addEventListener("mouseleave", () => {
|
||||
previewBox.style.transform = "scale(1)";
|
||||
});
|
||||
previewBox.addEventListener("click", () => deselectAll());
|
||||
topRow.appendChild(previewBox);
|
||||
|
||||
// ---- 右侧列:提示词框 + 搜索框 ----
|
||||
const rightCol = document.createElement("div");
|
||||
Object.assign(rightCol.style, {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
flex: "1",
|
||||
minWidth: "0",
|
||||
height: `${THUMB_H}px`,
|
||||
boxSizing: "border-box",
|
||||
overflow: "hidden",
|
||||
});
|
||||
|
||||
// ---- 提示词文本框 ----
|
||||
const promptArea = document.createElement("textarea");
|
||||
promptArea.placeholder = "服装/发型提示词:选择模板后自动填入,也可随时手动编辑...";
|
||||
Object.assign(promptArea.style, {
|
||||
width: "100%",
|
||||
height: `${PROMPT_TEXTAREA_H}px`,
|
||||
minHeight: `${PROMPT_TEXTAREA_H}px`,
|
||||
maxHeight: `${PROMPT_TEXTAREA_H}px`,
|
||||
resize: "none",
|
||||
background: "#222",
|
||||
color: "#ddd",
|
||||
border: "1px solid #444",
|
||||
borderRadius: "6px",
|
||||
padding: "6px 8px",
|
||||
fontSize: "14px",
|
||||
fontFamily: "'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif",
|
||||
outline: "none",
|
||||
boxSizing: "border-box",
|
||||
overflow: "auto",
|
||||
display: "block",
|
||||
lineHeight: "1.5",
|
||||
transition: "border-color .2s",
|
||||
marginBottom: `${INNER_GAP}px`,
|
||||
flexShrink: "0",
|
||||
});
|
||||
promptArea.addEventListener("focus", () => {
|
||||
promptArea.style.borderColor = "#4CAF50";
|
||||
});
|
||||
promptArea.addEventListener("blur", () => {
|
||||
promptArea.style.borderColor = "#444";
|
||||
});
|
||||
promptArea.addEventListener("keydown", (e) => e.stopPropagation());
|
||||
promptArea.addEventListener("input", () => {
|
||||
if (promptWidget) {
|
||||
promptWidget.value = promptArea.value;
|
||||
const el = promptWidget.element;
|
||||
if (el) {
|
||||
const ta = el.tagName === "TEXTAREA" ? el : el.querySelector?.("textarea");
|
||||
if (ta) ta.value = promptArea.value;
|
||||
}
|
||||
}
|
||||
_lastSyncedValue = promptArea.value;
|
||||
saveSelectionState();
|
||||
});
|
||||
rightCol.appendChild(promptArea);
|
||||
|
||||
// ---- 搜索框 ----
|
||||
const searchWrapper = document.createElement("div");
|
||||
Object.assign(searchWrapper.style, {
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
marginBottom: "0px",
|
||||
marginTop: "0px",
|
||||
flexShrink: "0",
|
||||
});
|
||||
|
||||
const magnifier = document.createElement("div");
|
||||
magnifier.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#888" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10.5" cy="10.5" r="7"/><line x1="15.5" y1="15.5" x2="21" y2="21"/></svg>`;
|
||||
Object.assign(magnifier.style, {
|
||||
position: "absolute", left: "8px", top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
pointerEvents: "none", zIndex: "2",
|
||||
});
|
||||
searchWrapper.appendChild(magnifier);
|
||||
|
||||
const searchInput = document.createElement("input");
|
||||
searchInput.type = "text";
|
||||
searchInput.placeholder = "搜索模板(多个关键词用任意符号隔开,如:西装 领带 男...)";
|
||||
Object.assign(searchInput.style, {
|
||||
width: "100%",
|
||||
padding: "5px 26px 5px 28px",
|
||||
border: "1px solid #555", borderRadius: "4px",
|
||||
background: "#2a2a2a", color: "#e0e0e0",
|
||||
fontSize: "12px", outline: "none",
|
||||
boxSizing: "border-box",
|
||||
transition: "border-color .2s",
|
||||
});
|
||||
searchInput.addEventListener("focus", () => {
|
||||
searchInput.style.borderColor = "#4CAF50";
|
||||
});
|
||||
searchInput.addEventListener("blur", () => {
|
||||
searchInput.style.borderColor = "#555";
|
||||
});
|
||||
searchInput.addEventListener("keydown", (e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === "Escape") searchInput.blur();
|
||||
});
|
||||
searchInput.addEventListener("input", () => {
|
||||
searchQuery = searchInput.value.trim();
|
||||
isSearching = searchQuery.length > 0;
|
||||
clearBtn.style.display = isSearching ? "flex" : "none";
|
||||
renderGallery();
|
||||
});
|
||||
searchWrapper.appendChild(searchInput);
|
||||
|
||||
const clearBtn = document.createElement("div");
|
||||
clearBtn.textContent = "✕";
|
||||
Object.assign(clearBtn.style, {
|
||||
position: "absolute", right: "8px", top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
width: "16px", height: "16px",
|
||||
display: "none", alignItems: "center", justifyContent: "center",
|
||||
color: "#888", fontSize: "12px", fontWeight: "bold",
|
||||
cursor: "pointer", zIndex: "2",
|
||||
borderRadius: "50%",
|
||||
transition: "color .15s, background .15s",
|
||||
});
|
||||
clearBtn.addEventListener("mouseenter", () => {
|
||||
clearBtn.style.color = "#e0e0e0";
|
||||
clearBtn.style.background = "rgba(255,255,255,0.1)";
|
||||
});
|
||||
clearBtn.addEventListener("mouseleave", () => {
|
||||
clearBtn.style.color = "#888";
|
||||
clearBtn.style.background = "transparent";
|
||||
});
|
||||
clearBtn.addEventListener("click", () => {
|
||||
searchInput.value = "";
|
||||
searchQuery = "";
|
||||
isSearching = false;
|
||||
clearBtn.style.display = "none";
|
||||
searchInput.focus();
|
||||
renderGallery();
|
||||
});
|
||||
searchWrapper.appendChild(clearBtn);
|
||||
rightCol.appendChild(searchWrapper);
|
||||
|
||||
topRow.appendChild(rightCol);
|
||||
container.appendChild(topRow);
|
||||
|
||||
// ---- 画廊网格 ----
|
||||
const gallery = document.createElement("div");
|
||||
gallery.className = "goohai-clothing-gallery";
|
||||
Object.assign(gallery.style, {
|
||||
display: "grid",
|
||||
gridTemplateColumns: `repeat(auto-fill, ${THUMB_W}px)`,
|
||||
justifyContent: "start",
|
||||
gap: `${GAP}px`,
|
||||
width: "100%",
|
||||
maxHeight: `${3 * THUMB_H + 2 * GAP}px`,
|
||||
overflowY: "auto",
|
||||
paddingRight: "2px",
|
||||
scrollbarWidth: "thin",
|
||||
scrollbarColor: "#555 transparent",
|
||||
});
|
||||
gallery.addEventListener("wheel", (e) => e.stopPropagation());
|
||||
container.appendChild(gallery);
|
||||
|
||||
const scrollStyle = document.createElement("style");
|
||||
scrollStyle.textContent = `
|
||||
.goohai-clothing-gallery::-webkit-scrollbar { width: 6px; }
|
||||
.goohai-clothing-gallery::-webkit-scrollbar-thumb { background: #555; border-radius: 3px; }
|
||||
.goohai-clothing-gallery::-webkit-scrollbar-track { background: transparent; }
|
||||
`;
|
||||
container.appendChild(scrollStyle);
|
||||
|
||||
// ==================== 渲染左侧预览框 ====================
|
||||
|
||||
function renderPreviewBox(firstItem) {
|
||||
previewBox.innerHTML = "";
|
||||
const innerRadius = `${BORDER_RADIUS - BORDER_HIGHLIGHT}px`;
|
||||
|
||||
if (firstItem._kind === "none") {
|
||||
const placeholder = document.createElement("div");
|
||||
Object.assign(placeholder.style, {
|
||||
width: "100%", height: "100%",
|
||||
display: "flex", alignItems: "center", justifyContent: "center",
|
||||
background: "#2d2d2d", color: "#888", fontSize: "16px",
|
||||
borderRadius: innerRadius,
|
||||
});
|
||||
placeholder.textContent = "无";
|
||||
previewBox.appendChild(placeholder);
|
||||
previewBox.appendChild(createSelectedBadge());
|
||||
} else {
|
||||
const img = document.createElement("img");
|
||||
img.src = `/goohai/id_photo_image/${encodeURIComponent(firstItem.category)}/${encodeURIComponent(firstItem.filename)}`;
|
||||
Object.assign(img.style, {
|
||||
width: "100%", height: "100%",
|
||||
objectFit: "cover", display: "block",
|
||||
borderRadius: innerRadius,
|
||||
});
|
||||
img.onerror = function () {
|
||||
this.style.display = "none";
|
||||
createImageFallback(previewBox, firstItem.title, "100%", "100%", innerRadius);
|
||||
};
|
||||
previewBox.appendChild(img);
|
||||
previewBox.appendChild(createSelectedBadge());
|
||||
}
|
||||
|
||||
previewBox.title = firstItem.prompt || firstItem.title || "";
|
||||
}
|
||||
|
||||
// ==================== 渲染画廊 ====================
|
||||
|
||||
function renderGallery() {
|
||||
gallery.innerHTML = "";
|
||||
const { items, poolCount } = buildDisplayList();
|
||||
|
||||
renderPreviewBox(items[0]);
|
||||
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const showBorder = item._isSel;
|
||||
const cardRadius = showBorder
|
||||
? `${BORDER_RADIUS - BORDER_HIGHLIGHT}px`
|
||||
: `${BORDER_RADIUS}px`;
|
||||
|
||||
const card = document.createElement("div");
|
||||
Object.assign(card.style, {
|
||||
position: "relative", cursor: "pointer",
|
||||
width: `${THUMB_W}px`,
|
||||
height: `${THUMB_H}px`,
|
||||
border: showBorder
|
||||
? `${BORDER_HIGHLIGHT}px solid #4CAF50`
|
||||
: `1px solid transparent`,
|
||||
borderRadius: `${BORDER_RADIUS}px`,
|
||||
overflow: "hidden",
|
||||
transition: "border-color .15s, transform .1s",
|
||||
background: "#1e1e1e",
|
||||
flexShrink: "0",
|
||||
});
|
||||
card.addEventListener("mouseenter", () => {
|
||||
card.style.transform = "scale(1.03)";
|
||||
});
|
||||
card.addEventListener("mouseleave", () => {
|
||||
card.style.transform = "scale(1)";
|
||||
});
|
||||
|
||||
const img = document.createElement("img");
|
||||
img.src = `/goohai/id_photo_image/${encodeURIComponent(item.category)}/${encodeURIComponent(item.filename)}`;
|
||||
Object.assign(img.style, {
|
||||
width: `${THUMB_W}px`,
|
||||
height: `${THUMB_H}px`,
|
||||
objectFit: "cover",
|
||||
display: "block",
|
||||
borderRadius: cardRadius,
|
||||
});
|
||||
img.loading = "lazy";
|
||||
img.onerror = function () {
|
||||
this.style.display = "none";
|
||||
createImageFallback(card, item.title, `${THUMB_W}px`, `${THUMB_H}px`, cardRadius);
|
||||
};
|
||||
card.appendChild(img);
|
||||
|
||||
const label = document.createElement("div");
|
||||
Object.assign(label.style, {
|
||||
position: "absolute", bottom: "0", left: "0", right: "0",
|
||||
background: "linear-gradient(transparent, rgba(0,0,0,0.8))",
|
||||
color: "#e0e0e0", fontSize: "10px",
|
||||
padding: "8px 4px 3px", textAlign: "center",
|
||||
whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
|
||||
borderRadius: `0 0 ${BORDER_RADIUS}px ${BORDER_RADIUS}px`,
|
||||
});
|
||||
label.textContent = item.title;
|
||||
card.appendChild(label);
|
||||
|
||||
if (isSearching && item._kind === "item") {
|
||||
const badge = document.createElement("div");
|
||||
Object.assign(badge.style, {
|
||||
position: "absolute", top: "2px", left: "2px",
|
||||
background: "rgba(0,0,0,0.7)", color: "#aaa",
|
||||
fontSize: "9px", padding: "1px 4px", borderRadius: "2px",
|
||||
});
|
||||
badge.textContent = item.category;
|
||||
card.appendChild(badge);
|
||||
}
|
||||
|
||||
card.title = item.prompt || item.title;
|
||||
|
||||
if (item._isSel) {
|
||||
card.appendChild(createCheckmark());
|
||||
card.addEventListener("click", deselectAll);
|
||||
} else {
|
||||
card.addEventListener("click", () => selectTemplate(item));
|
||||
}
|
||||
|
||||
gallery.appendChild(card);
|
||||
}
|
||||
|
||||
if (isSearching && poolCount === 0) {
|
||||
const noResult = document.createElement("div");
|
||||
Object.assign(noResult.style, {
|
||||
gridColumn: "1 / -1", textAlign: "center",
|
||||
color: "#666", padding: "16px", fontSize: "12px",
|
||||
});
|
||||
noResult.textContent = "未找到匹配的模板";
|
||||
gallery.appendChild(noResult);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 添加 DOM Widget ====================
|
||||
|
||||
const galleryWidget = node.addDOMWidget("clothing_gallery", "div", container, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
});
|
||||
|
||||
galleryWidget.computeSize = () => [0, 0];
|
||||
|
||||
if (promptWidget) {
|
||||
promptWidget.computeSize = () => [0, 0];
|
||||
if (promptWidget.element) {
|
||||
promptWidget.element.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 画廊高度自适应 ====================
|
||||
|
||||
function getLayoutMetrics() {
|
||||
const TITLE_H = (typeof LiteGraph !== 'undefined' && LiteGraph.NODE_TITLE_HEIGHT) || 30;
|
||||
const SLOT_H = (typeof LiteGraph !== 'undefined' && LiteGraph.NODE_SLOT_HEIGHT) || 20;
|
||||
return { TITLE_H, SLOT_H };
|
||||
}
|
||||
|
||||
function getContainerFixedOverhead() {
|
||||
return 8 + THUMB_H + 6;
|
||||
}
|
||||
|
||||
function updateGalleryHeight() {
|
||||
const { TITLE_H, SLOT_H } = getLayoutMetrics();
|
||||
const nodeH = node.size[1];
|
||||
if (!nodeH || nodeH <= 0) return;
|
||||
|
||||
const catH = SLOT_H;
|
||||
const avail = nodeH - TITLE_H - catH - getContainerFixedOverhead() - BOTTOM_PAD;
|
||||
const minH = THUMB_H + GAP;
|
||||
const maxH = Math.max(minH, avail);
|
||||
|
||||
if (Math.abs(maxH - _lastAppliedMaxH) < 1) return;
|
||||
_lastAppliedMaxH = maxH;
|
||||
|
||||
gallery.style.maxHeight = maxH + "px";
|
||||
}
|
||||
|
||||
const origOnResize = node.onResize;
|
||||
node.onResize = function (size) {
|
||||
if (origOnResize) origOnResize.call(node, size);
|
||||
requestAnimationFrame(updateGalleryHeight);
|
||||
};
|
||||
|
||||
const _pollId = setInterval(() => {
|
||||
if (!node.graph) { clearInterval(_pollId); return; }
|
||||
updateGalleryHeight();
|
||||
}, 200);
|
||||
|
||||
// ==================== 同步外部值变化 ====================
|
||||
|
||||
const _syncPollId = setInterval(() => {
|
||||
if (!node.graph) { clearInterval(_syncPollId); return; }
|
||||
const current = promptWidget?.value || "";
|
||||
if (current !== _lastSyncedValue) {
|
||||
_lastSyncedValue = current;
|
||||
promptArea.value = current;
|
||||
selectedPrompt = current;
|
||||
saveSelectionState();
|
||||
}
|
||||
}, 300);
|
||||
|
||||
// ==================== 节点移除时清理定时器 ====================
|
||||
|
||||
const origOnRemoved = node.onRemoved;
|
||||
node.onRemoved = function () {
|
||||
clearInterval(_pollId);
|
||||
clearInterval(_syncPollId);
|
||||
origOnRemoved?.apply(this, arguments);
|
||||
};
|
||||
|
||||
// ==================== 状态恢复 ====================
|
||||
|
||||
function tryLegacyRestore() {
|
||||
const saved = promptWidget?.value || "";
|
||||
if (!saved) return false;
|
||||
|
||||
for (const cat of allCategories) {
|
||||
const tpl = (allTemplates[cat] || []).find(t => t.prompt === saved);
|
||||
if (tpl) {
|
||||
selectedCategory = cat;
|
||||
selectedFilename = tpl.filename;
|
||||
selectedPrompt = tpl.prompt;
|
||||
currentCategory = cat;
|
||||
if (catWidget) catWidget.value = cat;
|
||||
promptArea.value = selectedPrompt;
|
||||
_lastSyncedValue = selectedPrompt;
|
||||
saveSelectionState();
|
||||
renderGallery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function restoreState() {
|
||||
const state = node.properties?._goohai_sel;
|
||||
if (!state) return tryLegacyRestore();
|
||||
|
||||
// 恢复当前浏览分类
|
||||
if (state.curCat && allCategories.includes(state.curCat)) {
|
||||
currentCategory = state.curCat;
|
||||
if (catWidget) catWidget.value = currentCategory;
|
||||
}
|
||||
|
||||
// 无选择状态
|
||||
if (state._none) {
|
||||
selectedCategory = "";
|
||||
selectedFilename = "";
|
||||
selectedPrompt = state.prompt ?? "";
|
||||
syncPrompt();
|
||||
renderGallery();
|
||||
return true;
|
||||
}
|
||||
|
||||
// 恢复模板选择
|
||||
if (state.cat && state.file) {
|
||||
const tpl = findTemplate(state.cat, state.file);
|
||||
if (tpl) {
|
||||
selectedCategory = tpl.category;
|
||||
selectedFilename = tpl.filename;
|
||||
selectedPrompt = state.prompt ?? (tpl.prompt || "");
|
||||
syncPrompt();
|
||||
renderGallery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return tryLegacyRestore();
|
||||
}
|
||||
|
||||
// ==================== 初始渲染 ====================
|
||||
|
||||
if (!restoreState()) {
|
||||
const defaultList = allTemplates[defaultCat] || [];
|
||||
if (defaultList.length > 0) {
|
||||
selectedCategory = defaultCat;
|
||||
const idx = Math.min(4, defaultList.length - 1);
|
||||
selectedFilename = defaultList[idx].filename;
|
||||
selectedPrompt = defaultList[idx].prompt;
|
||||
}
|
||||
syncPrompt();
|
||||
saveSelectionState();
|
||||
}
|
||||
|
||||
renderGallery();
|
||||
|
||||
// 首次打开时固定节点大小
|
||||
setTimeout(() => {
|
||||
const { TITLE_H, SLOT_H } = getLayoutMetrics();
|
||||
const defaultGalleryH = 3 * THUMB_H + 2 * GAP;
|
||||
const nodeSize = node.computeSize();
|
||||
const targetW = Math.max(nodeSize[0], GALLERY_WIDTH + 40);
|
||||
const targetH = TITLE_H + SLOT_H + getContainerFixedOverhead() + defaultGalleryH + BOTTOM_PAD;
|
||||
|
||||
gallery.style.maxHeight = defaultGalleryH + "px";
|
||||
node.setSize([targetW, targetH]);
|
||||
updateGalleryHeight();
|
||||
}, 100);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,908 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "goohaitools.ignore_groups",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "忽略多组孤海") return;
|
||||
|
||||
const origCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
origCreated?.apply(this, arguments);
|
||||
this.size = [400, this.size[1]];
|
||||
buildIgnoreGroupsUI(this);
|
||||
};
|
||||
|
||||
const origConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origConfigure?.apply(this, arguments);
|
||||
if (this._guhaiSyncGroups) this._guhaiSyncGroups();
|
||||
};
|
||||
|
||||
/* 右键上下文菜单 */
|
||||
const origGetExtra = nodeType.prototype.getExtraMenuOptions;
|
||||
nodeType.prototype.getExtraMenuOptions = function (canvas, options) {
|
||||
if (origGetExtra) origGetExtra.apply(this, arguments);
|
||||
options.unshift({
|
||||
content: "🎮 忽略多组_孤海 设置",
|
||||
callback: () => {
|
||||
if (this._guhaiShowSettings) {
|
||||
this._guhaiShowSettings(
|
||||
Math.round(innerWidth / 2 - 130),
|
||||
Math.round(innerHeight / 2 - 200)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
function buildIgnoreGroupsUI(node) {
|
||||
|
||||
/* ═══════════════════ 状态 ═══════════════════ */
|
||||
let filter = "";
|
||||
let mode = "default";
|
||||
let active = null;
|
||||
let activeSet = null;
|
||||
let nameColor = null;
|
||||
let igDisable = false;
|
||||
let selfChanging = false;
|
||||
let dirty = true;
|
||||
|
||||
if (node.properties) {
|
||||
if (node.properties.guhai_ig_filter != null) filter = node.properties.guhai_ig_filter;
|
||||
if (node.properties.guhai_ig_mode != null) mode = node.properties.guhai_ig_mode;
|
||||
if (node.properties.guhai_ig_active != null) active = node.properties.guhai_ig_active;
|
||||
if (node.properties.guhai_ig_active_set != null) activeSet = node.properties.guhai_ig_active_set;
|
||||
if (node.properties.guhai_ig_name_color != null) nameColor = node.properties.guhai_ig_name_color;
|
||||
if (node.properties.guhai_ig_disable != null) igDisable = !!node.properties.guhai_ig_disable;
|
||||
}
|
||||
|
||||
function save() {
|
||||
node.properties = node.properties || {};
|
||||
node.properties.guhai_ig_filter = filter;
|
||||
node.properties.guhai_ig_mode = mode;
|
||||
node.properties.guhai_ig_active = active;
|
||||
node.properties.guhai_ig_active_set = activeSet;
|
||||
node.properties.guhai_ig_name_color = nameColor;
|
||||
node.properties.guhai_ig_disable = igDisable;
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ Canvas 布局常量 ═══════════════════ */
|
||||
const HEADER_H = 14;
|
||||
const ROW_H = 34;
|
||||
const ROW_GAP = 15;
|
||||
const PAD_X = 16;
|
||||
const ROW_PAD_L = 26;
|
||||
const ROW_PAD_R = 16;
|
||||
const TOGGLE_W = 67;
|
||||
const TOGGLE_H = 26;
|
||||
const KNOB_R = 11;
|
||||
|
||||
|
||||
/* ═══════════════════ 几何工具 ═══════════════════ */
|
||||
function gBounds(g) {
|
||||
if (g._bounding) return [...g._bounding];
|
||||
if (g.bounding) return [...g.bounding];
|
||||
const p = g.pos || [0, 0], s = g.size || [0, 0];
|
||||
return [p[0], p[1], s[0], s[1]];
|
||||
}
|
||||
|
||||
function nBounds(n) {
|
||||
const p = n.pos || [0, 0], s = n.size || [100, 60];
|
||||
return [p[0], p[1], s[0], s[1]];
|
||||
}
|
||||
|
||||
function hit(a, b) {
|
||||
return !(a[0] + a[2] <= b[0] || a[0] >= b[0] + b[2] ||
|
||||
a[1] + a[3] <= b[1] || a[1] >= b[1] + b[3]);
|
||||
}
|
||||
|
||||
function inside(inner, outer) {
|
||||
return inner[0] >= outer[0] && inner[1] >= outer[1] &&
|
||||
inner[0] + inner[2] <= outer[0] + outer[2] &&
|
||||
inner[1] + inner[3] <= outer[1] + outer[3];
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ 组数据 ═══════════════════ */
|
||||
function rawGroups() {
|
||||
const g = app.graph;
|
||||
if (!g || !g._groups) return [];
|
||||
return g._groups.map(gr => ({
|
||||
title: (gr.title || "").trim() || "Unnamed",
|
||||
bounds: gBounds(gr),
|
||||
ref: gr,
|
||||
}));
|
||||
}
|
||||
|
||||
function visible() {
|
||||
let list = rawGroups();
|
||||
if (filter.trim()) {
|
||||
const kw = filter.trim().toLowerCase();
|
||||
list = list.filter(g => g.title.toLowerCase().includes(kw));
|
||||
}
|
||||
list.sort((a, b) =>
|
||||
a.title.localeCompare(b.title, undefined, { sensitivity: "base" })
|
||||
);
|
||||
return list;
|
||||
}
|
||||
|
||||
function collectNodes(grp) {
|
||||
const g = app.graph;
|
||||
if (!g || !g._nodes) return [];
|
||||
const all = rawGroups();
|
||||
const pb = grp.bounds;
|
||||
const rects = [pb];
|
||||
all.forEach(ag => {
|
||||
if (ag.ref !== grp.ref && inside(ag.bounds, pb)) {
|
||||
rects.push(ag.bounds);
|
||||
}
|
||||
});
|
||||
return g._nodes.filter(n => {
|
||||
const nb = nBounds(n);
|
||||
return rects.some(r => hit(nb, r));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/* 递归获取所有完全嵌套的子组 */
|
||||
function getAllNestedGroups(parentGroup) {
|
||||
const all = rawGroups();
|
||||
const result = [];
|
||||
const visited = new Set();
|
||||
visited.add(parentGroup.ref);
|
||||
|
||||
function findNested(parent) {
|
||||
all.forEach(ag => {
|
||||
if (!visited.has(ag.ref) && inside(ag.bounds, parent.bounds)) {
|
||||
visited.add(ag.ref);
|
||||
result.push(ag);
|
||||
findNested(ag);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
findNested(parentGroup);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ 旁路 / 恢复 ═══════════════════ */
|
||||
function bypassGroup(grp) {
|
||||
collectNodes(grp).forEach(n => {
|
||||
if (igDisable) {
|
||||
n.mode = 2;
|
||||
} else {
|
||||
n.mode = 4;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function restoreGroup(grp) {
|
||||
collectNodes(grp).forEach(n => {
|
||||
n.mode = 0;
|
||||
if (n.flags) n.flags.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
function isNodeActive(n) {
|
||||
return n.mode !== 4 && n.mode !== 2 && !n.flags?.disabled;
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ 组状态检测与外部同步 ═══════════════════ */
|
||||
|
||||
|
||||
function getGroupState(grp) {
|
||||
const nodes = collectNodes(grp);
|
||||
if (nodes.length === 0) return true;
|
||||
const allActive = nodes.every(n => isNodeActive(n));
|
||||
const allInactive = nodes.every(n => !isNodeActive(n));
|
||||
if (allActive) return true;
|
||||
if (allInactive) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
/* 计算所有组状态签名(用于检测外部变化) */
|
||||
function computeStateSig(list) {
|
||||
return list.map(g => {
|
||||
const s = getGroupState(g);
|
||||
return g.title + ":" + (s === true ? "1" : s === false ? "0" : "m");
|
||||
}).join("\x00");
|
||||
}
|
||||
|
||||
/* 将外部操作引起的节点状态变化同步到 activeSet / active */
|
||||
function syncExternalState() {
|
||||
const list = visible();
|
||||
let changed = false;
|
||||
|
||||
if (mode === "default") {
|
||||
if (!Array.isArray(activeSet)) return;
|
||||
list.forEach(g => {
|
||||
const gs = getGroupState(g);
|
||||
const isActive = activeSet.includes(g.title);
|
||||
if (gs === true && !isActive) {
|
||||
/* 全部激活 → 开关打开 */
|
||||
activeSet.push(g.title);
|
||||
changed = true;
|
||||
} else if (gs === false && isActive) {
|
||||
/* 全部绕过/禁用 → 开关关闭 */
|
||||
activeSet = activeSet.filter(t => t !== g.title);
|
||||
changed = true;
|
||||
}
|
||||
/* 混合状态 → 保持当前开关不变 */
|
||||
});
|
||||
} else if (mode === "at_most_one") {
|
||||
/* at_most_one:仅处理"关闭"方向 */
|
||||
if (active) {
|
||||
const grp = list.find(g => g.title === active);
|
||||
if (grp && getGroupState(grp) === false) {
|
||||
active = null;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* always_one:不做自动同步,避免违反"始终开启1个"约束 */
|
||||
|
||||
if (changed) save();
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ Canvas 绘图辅助 ═══════════════════ */
|
||||
|
||||
function rrect(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||
ctx.arcTo(x, y + h, x, y, r);
|
||||
ctx.arcTo(x, y, x + w, y, r);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
function ellipsis(ctx, text, maxW) {
|
||||
if (ctx.measureText(text).width <= maxW) return text;
|
||||
let t = text;
|
||||
while (t.length > 1 && ctx.measureText(t + "…").width > maxW) {
|
||||
t = t.slice(0, -1);
|
||||
}
|
||||
return t + "…";
|
||||
}
|
||||
|
||||
function hexToRgba(hex, alpha) {
|
||||
if (!hex || hex.length < 7) return `rgba(120,120,120,${alpha})`;
|
||||
const r = parseInt(hex.slice(1, 3), 16);
|
||||
const g = parseInt(hex.slice(3, 5), 16);
|
||||
const b = parseInt(hex.slice(5, 7), 16);
|
||||
return `rgba(${r},${g},${b},${alpha})`;
|
||||
}
|
||||
|
||||
function drawGear(ctx, cx, cy, r) {
|
||||
const teeth = 8;
|
||||
const outerR = r;
|
||||
const innerR = r * 0.65;
|
||||
const holeR = r * 0.3;
|
||||
const step = (Math.PI * 2) / teeth;
|
||||
const q = step * 0.25;
|
||||
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < teeth; i++) {
|
||||
const a = i * step - Math.PI / 2;
|
||||
if (i === 0) {
|
||||
ctx.moveTo(cx + outerR * Math.cos(a - q), cy + outerR * Math.sin(a - q));
|
||||
} else {
|
||||
ctx.lineTo(cx + outerR * Math.cos(a - q), cy + outerR * Math.sin(a - q));
|
||||
}
|
||||
ctx.lineTo(cx + outerR * Math.cos(a + q), cy + outerR * Math.sin(a + q));
|
||||
const va = a + step / 2;
|
||||
ctx.lineTo(cx + innerR * Math.cos(va - q), cy + innerR * Math.sin(va - q));
|
||||
ctx.lineTo(cx + innerR * Math.cos(va + q), cy + innerR * Math.sin(va + q));
|
||||
}
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = "rgba(120,120,120,0.15)";
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = "rgba(120,120,120,0.4)";
|
||||
ctx.lineWidth = 1.2;
|
||||
ctx.stroke();
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, holeR, 0, Math.PI * 2);
|
||||
ctx.fillStyle = "#2a2a2a";
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = "rgba(153,153,153,0.6)";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ 核心刷新 ═══════════════════ */
|
||||
let lastSig = "";
|
||||
let lastStateSig = "";
|
||||
|
||||
function refresh(forceApply) {
|
||||
const list = visible();
|
||||
const sig = list.map(g => g.title).join("\x00");
|
||||
const listChanged = (sig !== lastSig);
|
||||
lastSig = sig;
|
||||
|
||||
let stateChanged = false;
|
||||
|
||||
if (mode === "default") {
|
||||
if (!Array.isArray(activeSet)) {
|
||||
/* 首次加载/复位时,根据每个组的实际节点状态来决定开关 */
|
||||
activeSet = [];
|
||||
list.forEach(g => {
|
||||
const gs = getGroupState(g);
|
||||
if (gs !== false) {
|
||||
|
||||
activeSet.push(g.title);
|
||||
}
|
||||
|
||||
});
|
||||
stateChanged = true;
|
||||
} else {
|
||||
const titles = new Set(list.map(g => g.title));
|
||||
const before = activeSet.length;
|
||||
activeSet = activeSet.filter(t => titles.has(t));
|
||||
if (activeSet.length !== before) stateChanged = true;
|
||||
}
|
||||
} else {
|
||||
if (active && !list.find(g => g.title === active)) {
|
||||
active = (mode === "always_one" && list.length) ? list[0].title : null;
|
||||
stateChanged = true;
|
||||
}
|
||||
if (mode === "always_one" && !active && list.length) {
|
||||
active = list[0].title;
|
||||
stateChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (stateChanged) save();
|
||||
|
||||
if (forceApply || stateChanged || listChanged) {
|
||||
selfChanging = true;
|
||||
try {
|
||||
list.forEach(g => {
|
||||
let isOn;
|
||||
if (mode === "default") {
|
||||
isOn = activeSet.includes(g.title);
|
||||
} else {
|
||||
isOn = (g.title === active);
|
||||
}
|
||||
if (isOn) restoreGroup(g);
|
||||
else bypassGroup(g);
|
||||
});
|
||||
try { app.graph.change(); } catch (_) { /* ignore */ }
|
||||
} finally {
|
||||
selfChanging = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ 切换逻辑 ═══════════════════ */
|
||||
function handleToggle(title) {
|
||||
if (mode === "default") {
|
||||
if (!Array.isArray(activeSet)) activeSet = [];
|
||||
|
||||
const list = visible();
|
||||
const grp = list.find(g => g.title === title);
|
||||
const idx = activeSet.indexOf(title);
|
||||
const turnOn = idx < 0;
|
||||
|
||||
if (turnOn) {
|
||||
if (!activeSet.includes(title)) activeSet.push(title);
|
||||
if (grp) {
|
||||
getAllNestedGroups(grp).forEach(ng => {
|
||||
if (!activeSet.includes(ng.title)) activeSet.push(ng.title);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const offSet = new Set();
|
||||
offSet.add(title);
|
||||
if (grp) {
|
||||
getAllNestedGroups(grp).forEach(ng => offSet.add(ng.title));
|
||||
}
|
||||
activeSet = activeSet.filter(t => !offSet.has(t));
|
||||
}
|
||||
} else if (mode === "always_one") {
|
||||
if (active === title) return;
|
||||
active = title;
|
||||
} else {
|
||||
if (active === title) {
|
||||
active = null;
|
||||
} else {
|
||||
active = title;
|
||||
}
|
||||
}
|
||||
save();
|
||||
refresh(true);
|
||||
}
|
||||
|
||||
|
||||
/* ═══════════════════ 选项设置 ═══════════════════ */
|
||||
function showSettings(x, y) {
|
||||
const old = document.getElementById("guhai_ig_pop");
|
||||
if (old) old.remove();
|
||||
|
||||
const pop = document.createElement("div");
|
||||
pop.id = "guhai_ig_pop";
|
||||
Object.assign(pop.style, {
|
||||
position: "fixed",
|
||||
left: Math.min(x, innerWidth - 280) + "px",
|
||||
top: Math.min(y, innerHeight - 460) + "px",
|
||||
background: "#2a2a2a",
|
||||
border: "1px solid #555",
|
||||
borderRadius: "8px",
|
||||
padding: "14px 18px",
|
||||
zIndex: "99999",
|
||||
minWidth: "250px",
|
||||
boxShadow: "0 4px 24px rgba(0,0,0,0.6)",
|
||||
color: "#e0e0e0",
|
||||
fontFamily: "inherit",
|
||||
});
|
||||
|
||||
/* ── 标题 ── */
|
||||
const titleEl = document.createElement("div");
|
||||
titleEl.textContent = "🎮 忽略多组_孤海 设置";
|
||||
Object.assign(titleEl.style, {
|
||||
fontSize: "15px", fontWeight: "bold", marginBottom: "14px",
|
||||
color: "#e0e0e0",
|
||||
borderBottom: "1px solid #444", paddingBottom: "8px",
|
||||
});
|
||||
pop.appendChild(titleEl);
|
||||
|
||||
/* ── 关闭方式(绕过 / 禁用)── */
|
||||
const dLabel = document.createElement("div");
|
||||
dLabel.textContent = "路由控制";
|
||||
Object.assign(dLabel.style, {
|
||||
fontSize: "13px", fontWeight: "bold", marginBottom: "6px",
|
||||
});
|
||||
pop.appendChild(dLabel);
|
||||
|
||||
const dRow = document.createElement("div");
|
||||
Object.assign(dRow.style, {
|
||||
display: "flex", alignItems: "center", gap: "20px",
|
||||
marginBottom: "14px",
|
||||
});
|
||||
|
||||
const dRadioBypass = document.createElement("input");
|
||||
dRadioBypass.type = "radio";
|
||||
dRadioBypass.name = "guhai_ig_close_mode";
|
||||
dRadioBypass.value = "bypass";
|
||||
dRadioBypass.checked = !igDisable;
|
||||
dRadioBypass.style.cursor = "pointer";
|
||||
|
||||
const dLblBypass = document.createElement("label");
|
||||
dLblBypass.style.cursor = "pointer";
|
||||
dLblBypass.style.fontSize = "13px";
|
||||
dLblBypass.appendChild(dRadioBypass);
|
||||
dLblBypass.appendChild(document.createTextNode(" 绕过(ctrl+b)"));
|
||||
|
||||
const dRadioDisable = document.createElement("input");
|
||||
dRadioDisable.type = "radio";
|
||||
dRadioDisable.name = "guhai_ig_close_mode";
|
||||
dRadioDisable.value = "disable";
|
||||
dRadioDisable.checked = !!igDisable;
|
||||
dRadioDisable.style.cursor = "pointer";
|
||||
|
||||
const dLblDisable = document.createElement("label");
|
||||
dLblDisable.style.cursor = "pointer";
|
||||
dLblDisable.style.fontSize = "13px";
|
||||
dLblDisable.appendChild(dRadioDisable);
|
||||
dLblDisable.appendChild(document.createTextNode(" 禁用(ctrl+m)"));
|
||||
|
||||
dRow.appendChild(dLblBypass);
|
||||
dRow.appendChild(dLblDisable);
|
||||
pop.appendChild(dRow);
|
||||
|
||||
/* ── 筛选关键词 ── */
|
||||
const fLabel = document.createElement("div");
|
||||
fLabel.textContent = "筛选关键词";
|
||||
Object.assign(fLabel.style, {
|
||||
fontSize: "13px", fontWeight: "bold", marginBottom: "4px",
|
||||
});
|
||||
pop.appendChild(fLabel);
|
||||
|
||||
const fInput = document.createElement("input");
|
||||
fInput.type = "text";
|
||||
fInput.value = filter;
|
||||
fInput.placeholder = "留空 = 显示所有组";
|
||||
Object.assign(fInput.style, {
|
||||
width: "100%", padding: "5px 8px", fontSize: "13px",
|
||||
background: "#1a1a1a", border: "1px solid #555", borderRadius: "4px",
|
||||
color: "#e0e0e0", outline: "none", boxSizing: "border-box",
|
||||
marginBottom: "14px",
|
||||
});
|
||||
pop.appendChild(fInput);
|
||||
|
||||
/* ── 切换模式 ── */
|
||||
const mLabel = document.createElement("div");
|
||||
mLabel.textContent = "切换模式";
|
||||
Object.assign(mLabel.style, {
|
||||
fontSize: "13px", fontWeight: "bold", marginBottom: "4px",
|
||||
});
|
||||
pop.appendChild(mLabel);
|
||||
|
||||
const mSelect = document.createElement("select");
|
||||
Object.assign(mSelect.style, {
|
||||
width: "100%", padding: "5px 8px", fontSize: "13px",
|
||||
background: "#1a1a1a", border: "1px solid #555", borderRadius: "4px",
|
||||
color: "#e0e0e0", outline: "none", boxSizing: "border-box",
|
||||
marginBottom: "14px",
|
||||
});
|
||||
[
|
||||
["default", "默认"],
|
||||
["always_one", "始终开启1个"],
|
||||
["at_most_one", "最多开启1个"],
|
||||
].forEach(([val, txt]) => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = val;
|
||||
opt.textContent = txt;
|
||||
mSelect.appendChild(opt);
|
||||
});
|
||||
mSelect.value = mode;
|
||||
pop.appendChild(mSelect);
|
||||
|
||||
/* ── 主题颜色 ── */
|
||||
const cLabel = document.createElement("div");
|
||||
cLabel.textContent = "主题颜色";
|
||||
Object.assign(cLabel.style, {
|
||||
fontSize: "13px", fontWeight: "bold", marginBottom: "4px",
|
||||
});
|
||||
pop.appendChild(cLabel);
|
||||
|
||||
const colorRow = document.createElement("div");
|
||||
Object.assign(colorRow.style, {
|
||||
display: "flex", alignItems: "center", gap: "8px",
|
||||
marginBottom: "16px",
|
||||
});
|
||||
|
||||
const cInput = document.createElement("input");
|
||||
cInput.type = "color";
|
||||
cInput.value = nameColor || "#ac8686";
|
||||
Object.assign(cInput.style, {
|
||||
width: "36px", height: "28px", padding: "0",
|
||||
border: "1px solid #555", borderRadius: "4px",
|
||||
background: "#1a1a1a", cursor: "pointer",
|
||||
});
|
||||
colorRow.appendChild(cInput);
|
||||
|
||||
const cHex = document.createElement("input");
|
||||
cHex.type = "text";
|
||||
cHex.value = nameColor || "#ac8686";
|
||||
Object.assign(cHex.style, {
|
||||
flex: "1", padding: "5px 8px", fontSize: "13px",
|
||||
background: "#1a1a1a", border: "1px solid #555", borderRadius: "4px",
|
||||
color: "#e0e0e0", outline: "none", boxSizing: "border-box",
|
||||
});
|
||||
colorRow.appendChild(cHex);
|
||||
|
||||
cInput.addEventListener("input", () => { cHex.value = cInput.value; });
|
||||
cHex.addEventListener("input", () => {
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(cHex.value)) cInput.value = cHex.value;
|
||||
});
|
||||
pop.appendChild(colorRow);
|
||||
|
||||
/* ── 按钮 ── */
|
||||
const btnRow = document.createElement("div");
|
||||
Object.assign(btnRow.style, {
|
||||
display: "flex", justifyContent: "flex-end", gap: "8px",
|
||||
});
|
||||
|
||||
function makeBtn(text, bg, onClick) {
|
||||
const btn = document.createElement("button");
|
||||
btn.textContent = text;
|
||||
Object.assign(btn.style, {
|
||||
padding: "6px 22px", fontSize: "15.6px", background: bg,
|
||||
border: "none", borderRadius: "4px", color: "#fff",
|
||||
cursor: "pointer",
|
||||
});
|
||||
btn.addEventListener("click", onClick);
|
||||
return btn;
|
||||
}
|
||||
|
||||
btnRow.appendChild(makeBtn("取消", "#606060", () => pop.remove()));
|
||||
btnRow.appendChild(makeBtn("应用", "#4CAF50", () => {
|
||||
filter = fInput.value;
|
||||
const newMode = mSelect.value;
|
||||
nameColor = cInput.value || null;
|
||||
igDisable = dRadioDisable.checked;
|
||||
|
||||
if (newMode !== mode) {
|
||||
if (newMode === "default") {
|
||||
activeSet = visible().map(g => g.title);
|
||||
} else if (newMode === "always_one") {
|
||||
const list = visible();
|
||||
if (activeSet && activeSet.length) {
|
||||
active = activeSet[0];
|
||||
} else if (list.length) {
|
||||
active = list[0].title;
|
||||
} else {
|
||||
active = null;
|
||||
}
|
||||
activeSet = null;
|
||||
} else {
|
||||
const list = visible();
|
||||
if (activeSet && activeSet.length) {
|
||||
active = activeSet[0];
|
||||
} else if (mode === "always_one" && active) {
|
||||
/* keep */
|
||||
} else {
|
||||
active = null;
|
||||
}
|
||||
activeSet = null;
|
||||
}
|
||||
mode = newMode;
|
||||
} else {
|
||||
mode = newMode;
|
||||
if (mode === "always_one" && !active) {
|
||||
const list = visible();
|
||||
if (list.length) active = list[0].title;
|
||||
}
|
||||
}
|
||||
|
||||
save();
|
||||
refresh(true);
|
||||
pop.remove();
|
||||
}));
|
||||
pop.appendChild(btnRow);
|
||||
|
||||
document.body.appendChild(pop);
|
||||
fInput.focus();
|
||||
|
||||
setTimeout(() => {
|
||||
const handler = (e) => {
|
||||
if (!pop.contains(e.target)) {
|
||||
pop.remove();
|
||||
document.removeEventListener("mousedown", handler);
|
||||
}
|
||||
};
|
||||
document.addEventListener("mousedown", handler);
|
||||
}, 50);
|
||||
|
||||
pop.addEventListener("contextmenu", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
});
|
||||
}
|
||||
|
||||
node._guhaiShowSettings = showSettings;
|
||||
|
||||
|
||||
/* ═══════════════════ Canvas 自定义 Widget ═══════════════════ */
|
||||
let _w = 400, _y = 0;
|
||||
|
||||
node.addCustomWidget({
|
||||
name: "guhai_ig",
|
||||
type: "ig_custom",
|
||||
|
||||
/* ── 每帧绘制 ── */
|
||||
draw(ctx, node, widgetWidth, y, H) {
|
||||
_w = widgetWidth;
|
||||
_y = y;
|
||||
|
||||
const gearCX = widgetWidth - 18;
|
||||
const gearCY = y + HEADER_H / 2;
|
||||
drawGear(ctx, gearCX, gearCY, 5);
|
||||
|
||||
const list = visible();
|
||||
|
||||
if (!list.length) {
|
||||
ctx.font = "13px sans-serif";
|
||||
ctx.fillStyle = "#888";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(
|
||||
filter.trim() ? "无匹配的组" : "工作流中无编组",
|
||||
widgetWidth / 2,
|
||||
y + HEADER_H + 20
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const effectiveColor = nameColor || "#ac8686";
|
||||
|
||||
list.forEach((g, i) => {
|
||||
const rowX = PAD_X;
|
||||
const rowY = y + HEADER_H + i * (ROW_H + ROW_GAP);
|
||||
const rowW = widgetWidth - PAD_X * 2;
|
||||
const isOn = mode === "default"
|
||||
? activeSet.includes(g.title)
|
||||
: g.title === active;
|
||||
|
||||
/* 胶囊背景填充 */
|
||||
rrect(ctx, rowX, rowY, rowW, ROW_H, ROW_H / 2);
|
||||
ctx.fillStyle = "#2B2F38";
|
||||
ctx.fill();
|
||||
|
||||
/* 胶囊边框描边 */
|
||||
rrect(ctx, rowX, rowY, rowW, ROW_H, ROW_H / 2);
|
||||
ctx.strokeStyle = "#6E7581";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
|
||||
/* 开关轨道 —— 颜色由主题色控制 */
|
||||
const tx = rowX + rowW - ROW_PAD_R - TOGGLE_W;
|
||||
const ty = rowY + (ROW_H - TOGGLE_H) / 2;
|
||||
|
||||
ctx.save();
|
||||
if (isOn) {
|
||||
ctx.shadowColor = hexToRgba(effectiveColor, 0.35);
|
||||
ctx.shadowBlur = 10;
|
||||
ctx.fillStyle = effectiveColor;
|
||||
} else {
|
||||
ctx.shadowColor = "transparent";
|
||||
ctx.shadowBlur = 0;
|
||||
ctx.fillStyle = "#606060";
|
||||
}
|
||||
rrect(ctx, tx, ty, TOGGLE_W, TOGGLE_H, TOGGLE_H / 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
/* 旋钮 */
|
||||
const kx = isOn ? tx + TOGGLE_W - KNOB_R - 3 : tx + KNOB_R + 3;
|
||||
const ky = ty + TOGGLE_H / 2;
|
||||
|
||||
ctx.save();
|
||||
ctx.shadowColor = "rgba(0,0,0,0.3)";
|
||||
ctx.shadowBlur = 4;
|
||||
ctx.fillStyle = isOn ? "rgb(230,230,230)" : "rgb(128,128,128)";
|
||||
ctx.beginPath();
|
||||
ctx.arc(kx, ky, KNOB_R, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
/* 标签文字 */
|
||||
const textX = rowX + ROW_PAD_L;
|
||||
const maxTextW = tx - textX - 10;
|
||||
ctx.save();
|
||||
ctx.globalAlpha = isOn ? 1.0 : 0.5;
|
||||
ctx.font = "bold 20px sans-serif";
|
||||
ctx.fillStyle = effectiveColor;
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(
|
||||
ellipsis(ctx, g.title, maxTextW),
|
||||
textX,
|
||||
rowY + ROW_H / 2
|
||||
);
|
||||
ctx.restore();
|
||||
});
|
||||
},
|
||||
|
||||
/* ── 鼠标事件 ── */
|
||||
mouse(event, pos, node) {
|
||||
if (event.type !== "pointerdown" && event.type !== "mousedown") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const localX = pos[0];
|
||||
const localY = pos[1] - _y;
|
||||
|
||||
const gearCX = _w - 18;
|
||||
const gearCY = HEADER_H / 2;
|
||||
const gdx = localX - gearCX;
|
||||
const gdy = localY - gearCY;
|
||||
if (gdx * gdx + gdy * gdy < 7 * 7) {
|
||||
showSettings(event.clientX, event.clientY);
|
||||
return true;
|
||||
}
|
||||
|
||||
const list = visible();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const rowX = PAD_X;
|
||||
const rowY = HEADER_H + i * (ROW_H + ROW_GAP);
|
||||
const rowW = _w - PAD_X * 2;
|
||||
|
||||
if (localX >= rowX && localX <= rowX + rowW &&
|
||||
localY >= rowY && localY <= rowY + ROW_H) {
|
||||
handleToggle(list[i].title);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
computeSize(width) {
|
||||
const cnt = Math.max(visible().length, 1);
|
||||
return [400, HEADER_H + cnt * (ROW_H + ROW_GAP) - ROW_GAP + 10];
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
/* ═══════════════════ 脏标记系统 ═══════════════════ */
|
||||
if (app.graph && typeof app.graph.change === "function") {
|
||||
const origGraphChange = app.graph.change;
|
||||
app.graph.change = function () {
|
||||
if (!selfChanging) dirty = true;
|
||||
return origGraphChange.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
|
||||
function onKeyDown(e) {
|
||||
if ((e.ctrlKey || e.metaKey) &&
|
||||
(e.key === "m" || e.key === "b" || e.key === "M" || e.key === "B")) {
|
||||
setTimeout(() => { dirty = true; }, 100);
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
|
||||
|
||||
/* ═══════════════════ 定时同步 ═══════════════════ */
|
||||
let pageVisible = !document.hidden;
|
||||
function onVisibilityChange() {
|
||||
const nowVisible = !document.hidden;
|
||||
if (nowVisible && !pageVisible) {
|
||||
pageVisible = true;
|
||||
dirty = true;
|
||||
} else {
|
||||
pageVisible = nowVisible;
|
||||
}
|
||||
}
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
|
||||
const timer = setInterval(() => {
|
||||
if (!node.graph) {
|
||||
clearInterval(timer);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!pageVisible || !dirty) return;
|
||||
dirty = false;
|
||||
|
||||
const list = visible();
|
||||
|
||||
const sig = list.map(g => g.title).join("\x00");
|
||||
const listChanged = (sig !== lastSig);
|
||||
const stateSig = computeStateSig(list);
|
||||
const stateChanged = (stateSig !== lastStateSig);
|
||||
|
||||
if (listChanged || stateChanged) {
|
||||
lastStateSig = stateSig;
|
||||
|
||||
selfChanging = true;
|
||||
try {
|
||||
/* 同步外部状态变化到 activeSet / active */
|
||||
syncExternalState();
|
||||
/* 组列表变化时执行完整刷新(应用旁路/恢复) */
|
||||
if (listChanged) {
|
||||
refresh(false);
|
||||
}
|
||||
try { app.graph.change(); } catch (_) {}
|
||||
} finally {
|
||||
selfChanging = false;
|
||||
}
|
||||
}
|
||||
}, 500);
|
||||
|
||||
|
||||
/* ═══════════════════ 工作流加载后同步 ═══════════════════ */
|
||||
node._guhaiSyncGroups = () => {
|
||||
filter = (node.properties && node.properties.guhai_ig_filter) || "";
|
||||
mode = (node.properties && node.properties.guhai_ig_mode) || "default";
|
||||
active = (node.properties && node.properties.guhai_ig_active) || null;
|
||||
activeSet = (node.properties && node.properties.guhai_ig_active_set) || null;
|
||||
nameColor = (node.properties && node.properties.guhai_ig_name_color) || null;
|
||||
igDisable = (node.properties && node.properties.guhai_ig_disable) || false;
|
||||
lastSig = "";
|
||||
lastStateSig = "";
|
||||
dirty = true;
|
||||
refresh(true);
|
||||
};
|
||||
|
||||
|
||||
/* ═══════════════════ 初始构建 ═══════════════════ */
|
||||
refresh(false);
|
||||
lastStateSig = computeStateSig(visible());
|
||||
dirty = false;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
{
|
||||
"sources": [
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:__init__.py",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "__init__.py",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/__init__.py",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/__init__.py",
|
||||
"local_file": "guhai____init__.py",
|
||||
"sha256": "6b820d7452bd1ef0c0eabee0a8bfe73e9bf570cf4796a8d7d993b15ca020a952",
|
||||
"retrieved_at": "2026-10-29T19:37:03.242554+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
49
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"WEB_DIRECTORY": [
|
||||
10,
|
||||
11
|
||||
],
|
||||
"dynamic_module_discovery": [
|
||||
17,
|
||||
28
|
||||
],
|
||||
"registration_merge": [
|
||||
30,
|
||||
44
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:extension.json",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "extension.json",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/extension.json",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/extension.json",
|
||||
"local_file": "guhai__extension.json",
|
||||
"sha256": "4275682d89ac4bf3b09ba235c6be7e4a201a2cdef2d5a3e7d01e344a8ed835f9",
|
||||
"retrieved_at": "2026-10-29T19:37:03.634229+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
37
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
37
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:nodes/自动分割图像.py",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "nodes/自动分割图像.py",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/nodes/%E8%87%AA%E5%8A%A8%E5%88%86%E5%89%B2%E5%9B%BE%E5%83%8F.py",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/nodes/%E8%87%AA%E5%8A%A8%E5%88%86%E5%89%B2%E5%9B%BE%E5%83%8F.py",
|
||||
"local_file": "guhai__nodes__自动分割图像.py",
|
||||
"sha256": "0889d9fe46fcfd6692bcfbd3b2c54dcdc06c7e0095352d3482b4794d22df8260",
|
||||
"retrieved_at": "2026-10-29T19:37:04.046841+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
172
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"crop_algorithm": [
|
||||
8,
|
||||
52
|
||||
],
|
||||
"return_types": [
|
||||
54,
|
||||
58
|
||||
],
|
||||
"schema": [
|
||||
60,
|
||||
73
|
||||
],
|
||||
"first_input_batch_only": [
|
||||
80,
|
||||
83
|
||||
],
|
||||
"grid_and_directory": [
|
||||
85,
|
||||
99
|
||||
],
|
||||
"format_and_counter": [
|
||||
101,
|
||||
119
|
||||
],
|
||||
"tile_trim_write_return": [
|
||||
121,
|
||||
163
|
||||
],
|
||||
"registration": [
|
||||
165,
|
||||
172
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:web/js/BOOLEAN.js",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "web/js/BOOLEAN.js",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/BOOLEAN.js",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/BOOLEAN.js",
|
||||
"local_file": "guhai__web__js__BOOLEAN.js",
|
||||
"sha256": "184ddb889362c770eff98bba23579b35e24c3a4dd684b97bfc588f42dfbe6d64",
|
||||
"retrieved_at": "2026-10-29T19:37:04.457911+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
230
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
230
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:web/js/GoohaiNote.js",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "web/js/GoohaiNote.js",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/GoohaiNote.js",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/GoohaiNote.js",
|
||||
"local_file": "guhai__web__js__GoohaiNote.js",
|
||||
"sha256": "5fb1f66f76e5519990afd400f315e209fdc36ed05beb1a8a56348d4830a47ae9",
|
||||
"retrieved_at": "2026-10-29T19:37:04.907463+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
930
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
930
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:web/js/colorWidget.js",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "web/js/colorWidget.js",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/colorWidget.js",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/colorWidget.js",
|
||||
"local_file": "guhai__web__js__colorWidget.js",
|
||||
"sha256": "7e1e02baa9ab773bdbb9247925fec87a07b5309ce1ef35dfdfdec15c5b2eef26",
|
||||
"retrieved_at": "2026-10-29T19:37:05.306831+00:00",
|
||||
"license": "GPL-3.0 inline notice credits AILab/1038lab; repository-wide license unknown",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
126
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
126
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:web/js/goohai_universal_slider.js",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "web/js/goohai_universal_slider.js",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/goohai_universal_slider.js",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/goohai_universal_slider.js",
|
||||
"local_file": "guhai__web__js__goohai_universal_slider.js",
|
||||
"sha256": "e93df36fcf4ecd0d4eb264518582da4cfb4df25ae915c796bb9cb749731f8f7e",
|
||||
"retrieved_at": "2026-10-29T19:37:05.726329+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
615
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
615
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:web/js/id_photo_clothing.js",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "web/js/id_photo_clothing.js",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/id_photo_clothing.js",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/id_photo_clothing.js",
|
||||
"local_file": "guhai__web__js__id_photo_clothing.js",
|
||||
"sha256": "11e6ccd015b17dd5c6ca2010829075372b751b898d21e3f61abe347c4f51d144",
|
||||
"retrieved_at": "2026-10-29T19:37:06.134916+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
755
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
755
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:web/js/nodes pass.js",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "web/js/nodes pass.js",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/nodes%20pass.js",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/web/js/nodes%20pass.js",
|
||||
"local_file": "guhai__web__js__nodes pass.js",
|
||||
"sha256": "17ab7504fef7aaaa2e3cf72028eaa5d9aa1e6688ba75fe434fc8f40e11d27130",
|
||||
"retrieved_at": "2026-10-29T19:37:06.533673+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
908
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
908
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "goohai/Goohaitools-comfyui@885cac3dd323d26a77b69ae904a9a344f0dee7d0:README.md",
|
||||
"repository": "https://github.com/goohai/Goohaitools-comfyui",
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"file": "README.md",
|
||||
"url": "https://github.com/goohai/Goohaitools-comfyui/blob/885cac3dd323d26a77b69ae904a9a344f0dee7d0/README.md",
|
||||
"raw_url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/885cac3dd323d26a77b69ae904a9a344f0dee7d0/README.md",
|
||||
"local_file": "guhai__README.md",
|
||||
"sha256": "634b819891c824e2086d9249dcf7421bcb33ca0a84737e825e4f2807fa440d0a",
|
||||
"retrieved_at": "2026-10-29T19:37:06.929256+00:00",
|
||||
"license": "unknown; no LICENSE in fixed tree",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"full_fixed_source": [
|
||||
1,
|
||||
1
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "christian-byrne/audio-separation-nodes-comfyui@5291831d7c321ab7a5192374482f9848dffee75b:src/crop.py",
|
||||
"repository": "https://github.com/christian-byrne/audio-separation-nodes-comfyui",
|
||||
"commit": "5291831d7c321ab7a5192374482f9848dffee75b",
|
||||
"file": "src/crop.py",
|
||||
"url": "https://github.com/christian-byrne/audio-separation-nodes-comfyui/blob/5291831d7c321ab7a5192374482f9848dffee75b/src/crop.py",
|
||||
"raw_url": "https://raw.githubusercontent.com/christian-byrne/audio-separation-nodes-comfyui/5291831d7c321ab7a5192374482f9848dffee75b/src/crop.py",
|
||||
"local_file": "crop.py",
|
||||
"sha256": "a2ac02bd7b42efd6de665c51edd7c698bb3ba97939574a9e06a99917a614f56c",
|
||||
"retrieved_at": "2026-10-29T19:38:20.080852+00:00",
|
||||
"license": "unknown; LICENSE referenced but absent at fixed commit/package",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
77
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"schema": [
|
||||
8,
|
||||
26
|
||||
],
|
||||
"return_types": [
|
||||
28,
|
||||
31
|
||||
],
|
||||
"parse_slice": [
|
||||
44,
|
||||
77
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"local_file": "useStringWidget.ts",
|
||||
"sha256": "b734a2584d558de501150e8011e1c16031f33778c2cd3b4c712f296ce4f05396",
|
||||
"retrieved_at": "2026-10-29T19:38:44.535452+00:00",
|
||||
"license": "GPL-3.0; reuse pinned frontend LICENSE in serialization-evidence",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
137
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"STRING_constructor": [
|
||||
110,
|
||||
137
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"local_file": "useBooleanWidget.ts",
|
||||
"sha256": "36f477f75561e0c7bfc2c6757906724f8ff2c8660ace26759f3f07493877fece",
|
||||
"retrieved_at": "2026-10-29T19:38:44.933154+00:00",
|
||||
"license": "GPL-3.0; reuse pinned frontend LICENSE in serialization-evidence",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
31
|
||||
]
|
||||
],
|
||||
"rule_locations": {
|
||||
"BOOLEAN_constructor": [
|
||||
6,
|
||||
31
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { isBooleanInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
|
||||
export const useBooleanWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isBooleanInputSpec(inputSpec)) {
|
||||
throw new Error(`Invalid input data: ${inputSpec}`)
|
||||
}
|
||||
|
||||
const defaultVal = inputSpec.default ?? false
|
||||
const options = {
|
||||
on: inputSpec.label_on,
|
||||
off: inputSpec.label_off
|
||||
}
|
||||
|
||||
return node.addWidget(
|
||||
'toggle',
|
||||
inputSpec.name,
|
||||
defaultVal,
|
||||
() => {},
|
||||
options
|
||||
)
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { isStringInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { app } from '@/scripts/app'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
|
||||
const TRACKPAD_DETECTION_THRESHOLD = 50
|
||||
|
||||
function addMultilineWidget(
|
||||
node: LGraphNode,
|
||||
name: string,
|
||||
opts: { defaultVal: string; placeholder?: string }
|
||||
) {
|
||||
const inputEl = document.createElement('textarea')
|
||||
inputEl.className = 'comfy-multiline-input'
|
||||
inputEl.value = opts.defaultVal
|
||||
inputEl.placeholder = opts.placeholder || name
|
||||
inputEl.spellcheck = useSettingStore().get('Comfy.TextareaWidget.Spellcheck')
|
||||
|
||||
const widget = node.addDOMWidget(name, 'customtext', inputEl, {
|
||||
getValue(): string {
|
||||
return inputEl.value
|
||||
},
|
||||
setValue(v: string) {
|
||||
inputEl.value = v
|
||||
}
|
||||
})
|
||||
|
||||
widget.inputEl = inputEl
|
||||
widget.options.minNodeSize = [400, 200]
|
||||
|
||||
inputEl.addEventListener('input', () => {
|
||||
widget.callback?.(widget.value)
|
||||
})
|
||||
|
||||
// Allow middle mouse button panning
|
||||
inputEl.addEventListener('pointerdown', (event: PointerEvent) => {
|
||||
if (event.button === 1) {
|
||||
app.canvas.processMouseDown(event)
|
||||
}
|
||||
})
|
||||
|
||||
inputEl.addEventListener('pointermove', (event: PointerEvent) => {
|
||||
if ((event.buttons & 4) === 4) {
|
||||
app.canvas.processMouseMove(event)
|
||||
}
|
||||
})
|
||||
|
||||
inputEl.addEventListener('pointerup', (event: PointerEvent) => {
|
||||
if (event.button === 1) {
|
||||
app.canvas.processMouseUp(event)
|
||||
}
|
||||
})
|
||||
|
||||
inputEl.addEventListener('wheel', (event: WheelEvent) => {
|
||||
const gesturesEnabled = useSettingStore().get(
|
||||
'LiteGraph.Pointer.TrackpadGestures'
|
||||
)
|
||||
const deltaX = event.deltaX
|
||||
const deltaY = event.deltaY
|
||||
|
||||
const canScrollY = inputEl.scrollHeight > inputEl.clientHeight
|
||||
const isHorizontal = Math.abs(deltaX) > Math.abs(deltaY)
|
||||
|
||||
// Prevent pinch zoom from zooming the page
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
app.canvas.processMouseWheel(event)
|
||||
return
|
||||
}
|
||||
|
||||
// Detect if this is likely a trackpad gesture vs mouse wheel
|
||||
// Trackpads usually have deltaX or smaller deltaY values (< TRACKPAD_DETECTION_THRESHOLD)
|
||||
// Mouse wheels typically have larger discrete deltaY values (>= TRACKPAD_DETECTION_THRESHOLD)
|
||||
const isLikelyTrackpad =
|
||||
Math.abs(deltaX) > 0 || Math.abs(deltaY) < TRACKPAD_DETECTION_THRESHOLD
|
||||
|
||||
// Trackpad gestures: when enabled, trackpad panning goes to canvas
|
||||
if (gesturesEnabled && isLikelyTrackpad) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
app.canvas.processMouseWheel(event)
|
||||
return
|
||||
}
|
||||
|
||||
// When gestures disabled: horizontal always goes to canvas (no horizontal scroll in textarea)
|
||||
if (isHorizontal) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
app.canvas.processMouseWheel(event)
|
||||
return
|
||||
}
|
||||
|
||||
// Vertical scrolling when gestures disabled: let textarea scroll if scrollable
|
||||
if (canScrollY) {
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
|
||||
// If textarea can't scroll vertically, pass to canvas
|
||||
event.preventDefault()
|
||||
app.canvas.processMouseWheel(event)
|
||||
})
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
export const useStringWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isStringInputSpec(inputSpec)) {
|
||||
throw new Error(`Invalid input data: ${inputSpec}`)
|
||||
}
|
||||
|
||||
const defaultVal = inputSpec.default ?? ''
|
||||
const multiline = inputSpec.multiline
|
||||
|
||||
const widget = multiline
|
||||
? addMultilineWidget(node, inputSpec.name, {
|
||||
defaultVal,
|
||||
placeholder: inputSpec.placeholder
|
||||
})
|
||||
: node.addWidget('text', inputSpec.name, defaultVal, () => {}, {})
|
||||
|
||||
if (typeof inputSpec.dynamicPrompts === 'boolean') {
|
||||
widget.dynamicPrompts = inputSpec.dynamicPrompts
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"crop_registry_member": "src/crop.py",
|
||||
"crop_registry_bytes_match": true,
|
||||
"registry_package_sha256": "0d39cf047e26f2d5fa08c64561af06d5479278eef15d773a38573a28e398d8c4",
|
||||
"registry_commit_binding": "unknown; not exposed by API",
|
||||
"guhai_tree_commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"guhai_license": "unknown; no LICENSE in full fixed tree",
|
||||
"no_fonts_or_models_fetched": true,
|
||||
"guhai_discovery": {
|
||||
"commit": "885cac3dd323d26a77b69ae904a9a344f0dee7d0",
|
||||
"url": "https://api.github.com/repos/goohai/Goohaitools-comfyui/git/trees/885cac3dd323d26a77b69ae904a9a344f0dee7d0?recursive=1",
|
||||
"sha256": "570d35a60ce093d2a62d4a6d4575af4e51d577948207cb82963a302a721dcff4",
|
||||
"local_file": "guhai-tree.json",
|
||||
"retrieved_at": "2026-10-29T19:36:44.945789+00:00",
|
||||
"license": "API tree metadata; repository-wide source license unknown",
|
||||
"tree_truncated": false,
|
||||
"font_blob_content_fetched": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user