Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e51759574 | ||
|
|
a6895201c8 | ||
|
|
c931fb843e |
@@ -0,0 +1,10 @@
|
||||
# DOGMA Nodes 1.0.54 / API Platform V2
|
||||
|
||||
- Native asynchronous API branches in one batch: Quantity is parallel repeats with distinct seeds; no Variant control.
|
||||
- Native Seedance reference/edit/extend and first/last-frame video workflows.
|
||||
- Shared native Comfy account balance, credit formatting and node price expressions.
|
||||
- Exact geometry SVG icons, independent vertical scrolling and wrapping reference tiles.
|
||||
- Reference paint/crop/flip/invert/resize/grow/blur/hole filling and optional native SAM3 prompt masks.
|
||||
- Workspace selection, filename/date/project/scene, output sidecars and project library filters.
|
||||
- rgthree-style generated/original hover comparison, shared-transform pan/zoom viewer, click-outside close and reveal output in Explorer.
|
||||
- Preserve previous DOGMA IDs and original source graphs. No new Python dependencies.
|
||||
@@ -0,0 +1,3 @@
|
||||
# DOGMA 1.0.55 / API Platform V3
|
||||
|
||||
Immediate UI shell; one-node workflow; native model dropdowns and sorted resolutions; separate video reference and first/last modes; input-only image references; fixed nested reference preview URL; in-browser folder selection and reveal; server-enforced project/scene hierarchy; Stop; progress/estimated time; luminous trail; original A/B geometry; collapsible filename controls. Preset and Custom dimensions retain native behavior.
|
||||
@@ -0,0 +1,3 @@
|
||||
# DOGMA 1.0.56 / API Platform V4
|
||||
|
||||
DOGMA artwork for controls and generation/error/result cards. Unified compact 28x14 toggles with native keyboard interaction. Neutral 24px reference icons replace the plus on hover without changing the background or border. Small system-prompt labels and gray prompt resize grip. Discreet compare cursor and separate folder selection / Explorer actions. Bundled Roboto Mono OFL font and original DOGMA loading video. Run repetitions with unique seeds in independent API branches. Exact SAM3 preview mask reused at Run. Persistent editor drafts, zoom/pan, full-size copy/preview. Automatic A/B and synchronized video comparison. Stable chronological grid, saved filename, original prompt, video duration, error visibility with five-second grace. Gray scrollbars, full-row menus, top-edge total progress and native Windows folder opener. Portable optional project/scene folders and native preset/Custom behavior preserved.
|
||||
@@ -185,3 +185,22 @@ does not change the EXR master or the model's working encoding.
|
||||
The single visible settings group contains independent generation and delivery
|
||||
producers. Delivery-only changes reuse the model branch while Comfy's relevant
|
||||
cache is available; this is not persistent recovery across server restarts.
|
||||
|
||||
|
||||
## API Platform V2 / 1.0.54
|
||||
|
||||
Open DOGMA_API_PLATFORM_V2.json and press APRI DOGMA / API PLATFORM.
|
||||
Quantity creates independent native asynchronous partner-node branches inside
|
||||
one prompt, with a distinct seed per request. Provider limits still apply.
|
||||
The original graphs are retained but inactive; use Run in the DOGMA panel.
|
||||
Includes image/video references, per-reference preparation, Seedance video,
|
||||
project library, workspace copies, Comfy credits/pricing and zoom comparison.
|
||||
Existing DOGMA and H3 workflows keep their identifiers.
|
||||
|
||||
|
||||
## API Platform V3 / 1.0.55
|
||||
Open DOGMA_API_PLATFORM_V3.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
|
||||
|
||||
|
||||
## API Platform V4 / 1.0.56
|
||||
Open DOGMA_API_PLATFORM_V4.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
|
||||
|
||||
+25
@@ -218,3 +218,28 @@ try:
|
||||
del _HDR152, _HDR152_NAMES
|
||||
except Exception as _hdr152_error:
|
||||
print("[DOGMA HDR controls] Unavailable; existing DOGMA nodes preserved:", _hdr152_error)
|
||||
|
||||
|
||||
# API Platform: additive launcher; all existing node identifiers remain valid.
|
||||
try:
|
||||
from .dogma_api_platform import NODE_CLASS_MAPPINGS as _API153, NODE_DISPLAY_NAME_MAPPINGS as _API153_NAMES
|
||||
if set(_API153).intersection(NODE_CLASS_MAPPINGS):
|
||||
raise RuntimeError("DOGMA API Platform: node ID collision")
|
||||
NODE_CLASS_MAPPINGS.update(_API153)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(_API153_NAMES)
|
||||
del _API153, _API153_NAMES
|
||||
except Exception as _api153_error:
|
||||
print("[DOGMA API Platform] Launcher unavailable; previous DOGMA nodes preserved:", _api153_error)
|
||||
|
||||
|
||||
# API Platform V2: reference preparation, project library and native video output.
|
||||
try:
|
||||
from .dogma_api_platform_v2 import NODE_CLASS_MAPPINGS as _APIV2, NODE_DISPLAY_NAME_MAPPINGS as _APIV2_NAMES, register_routes as _APIV2_ROUTES
|
||||
if set(_APIV2).intersection(NODE_CLASS_MAPPINGS):
|
||||
raise RuntimeError("DOGMA API V2: node ID collision")
|
||||
_APIV2_ROUTES()
|
||||
NODE_CLASS_MAPPINGS.update(_APIV2)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(_APIV2_NAMES)
|
||||
del _APIV2, _APIV2_NAMES, _APIV2_ROUTES
|
||||
except Exception as _apiv2_error:
|
||||
print("[DOGMA API V2] Unavailable; previous DOGMA nodes preserved:", _apiv2_error)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
"""DOGMA API Platform: additive, frontend-only launcher for native partner nodes."""
|
||||
|
||||
|
||||
class DOGMAAPIPlatformV1:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {"config": ("STRING", {"default": "{}", "multiline": True})}}
|
||||
|
||||
RETURN_TYPES = ()
|
||||
OUTPUT_NODE = True
|
||||
FUNCTION = "settings"
|
||||
CATEGORY = "DOGMA/API Platform"
|
||||
DESCRIPTION = "Open DOGMA API Platform. Generation uses the existing Comfy partner API nodes."
|
||||
|
||||
def settings(self, config):
|
||||
return {"ui": {"text": ["Apri DOGMA / API Platform e usa Run nel pannello."]}, "result": ()}
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"DOGMAAPIPlatformV1": DOGMAAPIPlatformV1}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"DOGMAAPIPlatformV1": "DOGMA / API Platform"}
|
||||
@@ -0,0 +1,438 @@
|
||||
"""Reference preparation, project output records and local workspace operations.
|
||||
|
||||
Generation remains in native partner API nodes, in independent async branches.
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
_WORKSPACES = set()
|
||||
_FRONTEND_CACHE = {}
|
||||
|
||||
|
||||
def _output():
|
||||
import folder_paths
|
||||
return Path(folder_paths.get_output_directory()).resolve()
|
||||
|
||||
|
||||
def _library():
|
||||
path = _output() / 'DOGMA' / 'API' / '.library'
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _clean(value):
|
||||
return re.sub(r'[^\w.-]+', '_', str(value or '').strip(), flags=re.UNICODE).strip('.')[:100]
|
||||
|
||||
|
||||
def _record(metadata, files, kind):
|
||||
data = json.loads(metadata)
|
||||
identifier = str(data.get('id', ''))
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}', identifier):
|
||||
raise ValueError('Identificatore output non valido.')
|
||||
data.update(kind=kind, images=files, status='completed', finished=int(time.time()*1000))
|
||||
root = _output()
|
||||
exported = []
|
||||
warning = ''
|
||||
workspace = Path(data['workspace']).expanduser().resolve() if data.get('workspace') else None
|
||||
# Only a directory selected through this browser session may be outside output.
|
||||
if workspace and not (workspace.is_relative_to(root) or str(workspace) in _WORKSPACES):
|
||||
warning = 'Copia nella cartella di lavoro non eseguita: riseleziona la cartella. Il file è salvato in Comfy output.'
|
||||
workspace = None
|
||||
if workspace:
|
||||
try:
|
||||
target = workspace
|
||||
for field in ('project', 'scene'):
|
||||
if _clean(data.get(field)):target /= _clean(data[field])
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for file in files:
|
||||
source = (root / file.get('subfolder', '') / file['filename']).resolve()
|
||||
if not source.is_relative_to(root):raise ValueError('Output non valido.')
|
||||
destination = target / source.name
|
||||
if destination != source:
|
||||
# Job IDs prevent a different project/run from replacing a file.
|
||||
if destination.exists():destination = target / (source.stem+'_'+identifier[:8]+source.suffix)
|
||||
shutil.copy2(source, destination)
|
||||
exported.append(str(destination))
|
||||
sidecar = target / (identifier+'.dogma.json')
|
||||
sidecar.write_text(json.dumps({**data, 'exported': exported, 'dogma_schema':3, 'workspace_relative':target.relative_to(workspace).as_posix()}, ensure_ascii=False, indent=2), encoding='utf8')
|
||||
except (OSError, ValueError) as exc:
|
||||
warning = 'File salvato in Comfy; copia nella cartella di lavoro non riuscita: '+str(exc)
|
||||
if not workspace:
|
||||
for file in files:
|
||||
target=root/file.get('subfolder','')
|
||||
(target/(identifier+'.dogma.json')).write_text(json.dumps({**data,'dogma_schema':3},ensure_ascii=False,indent=2),encoding='utf8')
|
||||
data['exported'] = exported
|
||||
if warning:data['warning'] = warning
|
||||
path = _library() / (identifier+'.json')
|
||||
temporary = path.with_suffix('.tmp')
|
||||
with _LOCK:
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False), encoding='utf8')
|
||||
temporary.replace(path)
|
||||
return data
|
||||
|
||||
|
||||
def _import_workspace(root):
|
||||
"""Portable sidecars travel with the output; no inference from filename tags."""
|
||||
root=Path(root).resolve();records=[];seen=set()
|
||||
from itertools import chain
|
||||
legacy=(p for directory in root.rglob('.library') if directory.is_dir() for p in directory.glob('*.json'))
|
||||
for path in chain(root.rglob('*.dogma.json'),legacy):
|
||||
if len(records)>=5000:break
|
||||
if not path.resolve().is_relative_to(root):continue
|
||||
try:
|
||||
data=json.loads(path.read_text('utf8'));identifier=str(data.get('id',''))
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):continue
|
||||
if identifier in seen:continue
|
||||
files=[];exported=[]
|
||||
for index,original in enumerate(data.get('images',[])):
|
||||
copies=data.get('exported',[])
|
||||
name=Path(copies[index].replace('\\','/')).name if index<len(copies) else Path(original.get('filename','')).name
|
||||
if path.parent.name=='.library':
|
||||
subfolder=str(original.get('subfolder','')).replace('\\','/')
|
||||
relative=subfolder.removeprefix('DOGMA/API').lstrip('/')
|
||||
candidate=(path.parent.parent/relative/name).resolve()
|
||||
else:candidate=(path.parent/name).resolve()
|
||||
if not candidate.is_relative_to(root) or not candidate.is_file():continue
|
||||
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace'})
|
||||
exported.append(str(candidate))
|
||||
if not files:continue
|
||||
data.update(workspace=str(root),images=files,exported=exported,status='completed',imported=True)
|
||||
(_library()/(identifier+'.json')).write_text(json.dumps(data,ensure_ascii=False),encoding='utf8')
|
||||
records.append(data);seen.add(identifier)
|
||||
except (ValueError,OSError,KeyError,TypeError):continue
|
||||
return records
|
||||
|
||||
|
||||
_SAM_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def prompt_mask(source, image, settings):
|
||||
"""Compute the installed SAM3 node once and retain the exact mask for Run."""
|
||||
import inspect
|
||||
import numpy as np
|
||||
import torch
|
||||
import nodes
|
||||
import folder_paths
|
||||
from PIL import Image
|
||||
prompt = str(settings.get('prompt', '')).strip()
|
||||
if not prompt:raise ValueError('Scrivi cosa selezionare in MASK PROMPT.')
|
||||
node_class = nodes.NODE_CLASS_MAPPINGS.get('SAM3Segment')
|
||||
if node_class is None:raise ValueError('SAM3 non è disponibile. Installa o abilita il nodo SAM3Segment di ComfyUI-RMBG e riavvia Comfy.')
|
||||
stat = source.stat()
|
||||
signature = json.dumps([str(source),stat.st_mtime_ns,stat.st_size,prompt,int(settings.get('segment') or 0),node_class.__module__],ensure_ascii=False)
|
||||
digest = hashlib.sha256(signature.encode()).hexdigest()
|
||||
directory = Path(folder_paths.get_input_directory())/'DOGMA_API'/'masks'
|
||||
directory.mkdir(parents=True,exist_ok=True)
|
||||
path = directory/('sam3_'+digest+'.png')
|
||||
with _SAM_LOCK:
|
||||
if not path.is_file():
|
||||
instance = node_class()
|
||||
function = getattr(instance,node_class.FUNCTION)
|
||||
specs = node_class.INPUT_TYPES()
|
||||
values = {}
|
||||
for name,spec in {**specs.get('required',{}),**specs.get('optional',{})}.items():
|
||||
options=spec[1] if len(spec)>1 and isinstance(spec[1],dict) else {}
|
||||
if 'default' in options:values[name]=options['default']
|
||||
elif isinstance(spec[0],list) and spec[0]:values[name]=spec[0][0]
|
||||
values.update(image=torch.from_numpy(np.asarray(image.convert('RGB')).copy()).float().unsqueeze(0)/255,prompt=prompt,output_mode='Merged',confidence_threshold=.5,max_segments=0,segment_pick=int(settings.get('segment') or 0),mask_blur=0,mask_offset=0,device='Auto',invert_output=False,unload_model=True,background='Alpha',background_color='#222222')
|
||||
parameters=inspect.signature(function).parameters
|
||||
values={key:value for key,value in values.items() if key in parameters}
|
||||
with torch.inference_mode():result=function(**values)
|
||||
if isinstance(result,dict):result=result.get('result',())
|
||||
if not result or len(result)<2:raise ValueError('SAM3 non ha restituito una maschera.')
|
||||
masks=result[1].detach().cpu()
|
||||
if masks.numel()==0:mask=Image.new('L',image.size,0)
|
||||
else:
|
||||
if masks.ndim==3:masks=masks.amax(dim=0)
|
||||
mask=Image.fromarray((masks.numpy().clip(0,1)*255).astype(np.uint8)).resize(image.size,Image.Resampling.NEAREST)
|
||||
temporary=path.with_suffix('.tmp')
|
||||
mask.save(temporary,format='PNG');temporary.replace(path)
|
||||
return Image.open(path).convert('L'), 'DOGMA_API/masks/'+path.name
|
||||
|
||||
|
||||
def process_reference(image, mask, settings):
|
||||
"""Shared Pillow operation used by the node and by the no-generation preview."""
|
||||
import numpy as np
|
||||
from PIL import Image, ImageOps, ImageFilter, ImageColor
|
||||
from scipy import ndimage
|
||||
cfg = json.loads(settings) if isinstance(settings, str) else settings
|
||||
image = image.convert('RGB')
|
||||
mask = mask.convert('L').resize(image.size, Image.Resampling.NEAREST)
|
||||
if cfg.get('flip'):
|
||||
image = ImageOps.mirror(image);mask = ImageOps.mirror(mask)
|
||||
if cfg.get('resizeMpx'):
|
||||
megapixels = max(.01, min(64, float(cfg.get('megapixels', 1))))
|
||||
scale = (megapixels*1e6/(image.width*image.height))**.5
|
||||
size = (max(1, round(image.width*scale)), max(1, round(image.height*scale)))
|
||||
image = image.resize(size, Image.Resampling.LANCZOS);mask = mask.resize(size, Image.Resampling.NEAREST)
|
||||
if cfg.get('invert'):mask = ImageOps.invert(mask)
|
||||
if cfg.get('fillHoles'):
|
||||
arr = np.asarray(mask);filled = ndimage.binary_fill_holes(arr>127)
|
||||
mask = Image.fromarray(np.maximum(arr, filled.astype(np.uint8)*255))
|
||||
grow = max(-512, min(512, int(cfg.get('expand', 0))))
|
||||
if grow:
|
||||
array = np.asarray(mask)
|
||||
fun = ndimage.maximum_filter if grow>0 else ndimage.minimum_filter
|
||||
mask = Image.fromarray(fun(array, size=abs(grow)*2+1))
|
||||
blur = max(0, min(128, float(cfg.get('blur', 0))))
|
||||
if blur:mask = mask.filter(ImageFilter.GaussianBlur(blur))
|
||||
crop_box = None
|
||||
if cfg.get('crop'):
|
||||
rect = cfg.get('cropRect')
|
||||
if rect:
|
||||
x,y,w,h = [max(0,min(1,float(n))) for n in rect]
|
||||
if cfg.get('flip'):x=max(0,1-x-w)
|
||||
crop_box = (round(x*image.width),round(y*image.height),round(min(1,x+w)*image.width),round(min(1,y+h)*image.height))
|
||||
else:crop_box = mask.point(lambda v:255 if v>25 else 0).getbbox()
|
||||
if not crop_box or crop_box[2]<=crop_box[0] or crop_box[3]<=crop_box[1]:
|
||||
raise ValueError('Crop vuoto: seleziona un’area o dipingi una maschera.')
|
||||
if cfg.get('mask'):
|
||||
background = Image.new('RGB', image.size, ImageColor.getrgb(cfg.get('background') or '#ff00ff'))
|
||||
image = Image.composite(background,image,mask) if cfg.get('maskMode')=='edit' else Image.composite(image,background,mask)
|
||||
if crop_box:image=image.crop(crop_box);mask=mask.crop(crop_box)
|
||||
width,height = int(cfg.get('targetWidth') or 0),int(cfg.get('targetHeight') or 0)
|
||||
if cfg.get('crop') and width>0 and height>0:
|
||||
if width>16384 or height>16384:raise ValueError('Dimensioni crop troppo grandi.')
|
||||
image=image.resize((width,height),Image.Resampling.LANCZOS);mask=mask.resize((width,height),Image.Resampling.NEAREST)
|
||||
return image,mask
|
||||
|
||||
|
||||
class DOGMAAPIReferenceV2:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {'required': {'image':('IMAGE',), 'mask':('MASK',), 'settings':('STRING',{'default':'{}'})}}
|
||||
RETURN_TYPES=('IMAGE',)
|
||||
FUNCTION='prepare'
|
||||
CATEGORY='DOGMA/API Platform'
|
||||
|
||||
def prepare(self,image,mask,settings):
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
results=[]
|
||||
for index in range(image.shape[0]):
|
||||
pil=Image.fromarray((image[index].detach().cpu().numpy().clip(0,1)*255).astype(np.uint8))
|
||||
alpha=Image.fromarray((mask[min(index,len(mask)-1)].detach().cpu().numpy().clip(0,1)*255).astype(np.uint8))
|
||||
processed,_=process_reference(pil,alpha,settings)
|
||||
results.append(torch.from_numpy(np.asarray(processed).copy()).float()/255)
|
||||
return (torch.stack(results),)
|
||||
|
||||
|
||||
def _save_prefix(data):
|
||||
basename=Path(str(data.get('prefix') or 'DOGMA').replace('\\','/')).name
|
||||
return '/'.join(['DOGMA','API',*[_clean(data.get(k)) for k in ('project','scene') if _clean(data.get(k))],basename])
|
||||
|
||||
|
||||
class DOGMAAPIImageOutputV2:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {'required':{'images':('IMAGE',),'metadata':('STRING',)},'hidden':{'prompt':'PROMPT','extra_pnginfo':'EXTRA_PNGINFO'}}
|
||||
RETURN_TYPES=()
|
||||
OUTPUT_NODE=True
|
||||
FUNCTION='save'
|
||||
CATEGORY='DOGMA/API Platform'
|
||||
|
||||
def save(self,images,metadata,prompt=None,extra_pnginfo=None):
|
||||
from nodes import SaveImage
|
||||
data=json.loads(metadata)
|
||||
# Same output and metadata behavior as the native SaveImage node.
|
||||
result=SaveImage().save_images(images,_save_prefix(data),prompt,extra_pnginfo)
|
||||
record=_record(metadata,result['ui']['images'],'image')
|
||||
return {'ui':{**result['ui'],'dogma_records':[record]},'result':()}
|
||||
|
||||
|
||||
class DOGMAAPIVideoOutputV2:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {'required':{'video':('VIDEO',),'metadata':('STRING',)},'hidden':{'prompt':'PROMPT','extra_pnginfo':'EXTRA_PNGINFO'}}
|
||||
RETURN_TYPES=()
|
||||
OUTPUT_NODE=True
|
||||
FUNCTION='save'
|
||||
CATEGORY='DOGMA/API Platform'
|
||||
|
||||
def save(self,video,metadata,prompt=None,extra_pnginfo=None):
|
||||
from comfy_api.latest import Types
|
||||
import folder_paths
|
||||
from comfy.cli_args import args
|
||||
data=json.loads(metadata);width,height=video.get_dimensions()
|
||||
folder,filename,counter,subfolder,_=folder_paths.get_save_image_path(_save_prefix(data),str(_output()),width,height)
|
||||
filename=f'{filename}_{counter:05}_.mp4'
|
||||
saved_metadata=None if args.disable_metadata else {**(extra_pnginfo or {}),'prompt':prompt}
|
||||
video.save_to(str(Path(folder)/filename),format=Types.VideoContainer('mp4'),codec=Types.VideoCodec('auto'),metadata=saved_metadata)
|
||||
files=[{'filename':filename,'subfolder':subfolder,'type':'output','format':'video/mp4'}]
|
||||
record=_record(metadata,files,'video')
|
||||
return {'ui':{'images':files,'animated':(True,),'dogma_records':[record]},'result':()}
|
||||
|
||||
|
||||
def frontend_modules(web_root):
|
||||
"""Discover the installed frontend's own shared billing/pricing modules."""
|
||||
cache_key=str(web_root)
|
||||
if cache_key in _FRONTEND_CACHE:return _FRONTEND_CACHE[cache_key]
|
||||
assets=Path(web_root)/'assets';result={}
|
||||
for path in assets.glob('*.js'):
|
||||
if path.name.startswith('useBillingContext-'):
|
||||
text=path.read_text('utf8');exports=text[text.rfind('export{'):]
|
||||
match=re.search(r'useNodePricing as (\w+)',exports)
|
||||
shared=re.search(r'(\w+)=\w+\(useBillingContextInternal\)',text)
|
||||
alias=re.search(r'\b'+re.escape(shared[1])+r' as (\w+)',exports) if shared else None
|
||||
if match and alias:result['billing']={'file':path.name,'context':alias[1],'pricing':match[1]}
|
||||
elif path.name.startswith('creditsUtil-'):
|
||||
text=path.read_text('utf8');match=re.search(r'formatCreditsFromCents as (\w+)',text)
|
||||
if match:result['credits']={'file':path.name,'format':match[1]}
|
||||
_FRONTEND_CACHE[cache_key]=result
|
||||
return result
|
||||
|
||||
|
||||
def register_routes():
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
from .dogma_h3_access import H3Access
|
||||
import folder_paths
|
||||
access=H3Access();routes=PromptServer.instance.routes
|
||||
|
||||
@routes.get('/dogma/api/v2/catalog')
|
||||
async def catalog(request):
|
||||
capabilities=access.catalog(request,_output())
|
||||
return web.json_response({'access':{**capabilities,'output_root':str(_output()/'DOGMA'/'API')},'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.56'})
|
||||
|
||||
@routes.post('/dogma/api/v2/workspace')
|
||||
async def workspace(request):
|
||||
access.browser(request);data=await request.json()
|
||||
try:
|
||||
path=access.output_path(request,data.get('path'),_output())
|
||||
if not path.is_dir():raise ValueError('Scegli una cartella esistente.')
|
||||
_WORKSPACES.add(str(path))
|
||||
records=await asyncio.to_thread(_import_workspace,path)
|
||||
return web.json_response({'path':str(path),'records':records})
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/choose-folder')
|
||||
async def choose(request):
|
||||
access.browser(request)
|
||||
return web.json_response({'browse':True})
|
||||
|
||||
@routes.get('/dogma/api/v2/folders')
|
||||
async def folders(request):
|
||||
access.browser(request)
|
||||
try:
|
||||
path=access.output_path(request,request.query.get('path') or str(_library().parent),_output())
|
||||
if not path.is_dir():raise ValueError('Cartella inesistente.')
|
||||
local=access.is_local(request)
|
||||
def scan():
|
||||
dirs=[];files=[]
|
||||
for p in path.iterdir():
|
||||
if p.name.startswith('.'):continue
|
||||
try:
|
||||
if not local and not p.resolve().is_relative_to(_output()):continue
|
||||
if p.is_dir():dirs.append({'name':p.name,'path':str(p.resolve())})
|
||||
elif p.is_file():files.append({'name':p.name})
|
||||
except OSError:continue
|
||||
parent=str(path.parent) if path.parent!=path and (local or path.parent.is_relative_to(_output())) else None
|
||||
roots=[]
|
||||
if local and os.name=='nt':
|
||||
roots=[{'name':letter+':','path':letter+':/'} for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if Path(letter+':/').is_dir()]
|
||||
return {'path':str(path),'parent':parent,'roots':roots,'directories':sorted(dirs,key=lambda d:d['name'].lower()),'files':sorted(files,key=lambda d:d['name'].lower())[:5000]}
|
||||
return web.json_response(await asyncio.to_thread(scan))
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/mkdir')
|
||||
async def mkdir(request):
|
||||
access.browser(request);data=await request.json()
|
||||
try:
|
||||
parent=access.output_path(request,data.get('path'),_output())
|
||||
name=str(data.get('name','')).strip()
|
||||
if not name or name in ('.','..') or re.search(r'[<>:"/\\|?*]',name) or name.endswith(('.', ' ')):raise ValueError('Nome cartella non valido.')
|
||||
target=parent/name
|
||||
if not parent.is_dir():raise ValueError('Cartella superiore inesistente.')
|
||||
target.mkdir(exist_ok=False)
|
||||
return web.json_response({'path':str(target.resolve())})
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.get('/dogma/api/v2/workspace-media')
|
||||
async def workspace_media(request):
|
||||
access.fetch_site(request)
|
||||
try:
|
||||
root=access.output_path(request,request.query.get('workspace'),_output())
|
||||
if str(root) not in _WORKSPACES:raise ValueError('Riseleziona la cartella di lavoro.')
|
||||
relative=request.query.get('relative','');file=(root/relative).resolve()
|
||||
if not file.is_relative_to(root) or file.suffix.lower() not in ('.png','.jpg','.jpeg','.webp','.mp4','.webm','.mov'):raise ValueError('File non valido.')
|
||||
if not file.is_file():raise ValueError('File non disponibile.')
|
||||
return web.FileResponse(file)
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.get('/dogma/api/v2/library')
|
||||
async def library(request):
|
||||
access.browser(request)
|
||||
def read():
|
||||
records=[]
|
||||
for path in sorted(_library().glob('*.json'),key=lambda p:p.stat().st_mtime,reverse=True)[:5000]:
|
||||
try:records.append(json.loads(path.read_text('utf8')))
|
||||
except (ValueError,OSError):continue
|
||||
return records
|
||||
return web.json_response({'records':await asyncio.to_thread(read)})
|
||||
|
||||
@routes.post('/dogma/api/v2/open-output')
|
||||
async def open_output(request):
|
||||
access.browser(request)
|
||||
data=await request.json();identifier=str(data.get('id',''))
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):raise web.HTTPBadRequest(text='Output non valido.')
|
||||
try:
|
||||
record=json.loads((_library()/(identifier+'.json')).read_text('utf8'))
|
||||
index=max(0,int(data.get('index',0)));copies=record.get('exported',[])
|
||||
file=Path(copies[index]) if index<len(copies) else _output()/record['images'][index].get('subfolder','')/record['images'][index]['filename']
|
||||
if not file.is_file():raise ValueError('Il file è stato spostato o rimosso.')
|
||||
access.output_path(request,str(file.parent),_output())
|
||||
return web.json_response({'path':str(file.parent),'filename':file.name})
|
||||
except (ValueError,OSError,IndexError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/explorer')
|
||||
async def explorer(request):
|
||||
access.browser(request)
|
||||
if not access.is_local(request) or os.name!='nt':
|
||||
raise web.HTTPBadRequest(text='Esplora file è disponibile sul computer Windows che esegue Comfy. Usa il browser cartelle su un server remoto.')
|
||||
data=await request.json()
|
||||
try:
|
||||
path=access.output_path(request,data.get('path'),_output())
|
||||
if not path.is_dir():raise ValueError('Cartella inesistente.')
|
||||
os.startfile(str(path))
|
||||
return web.json_response({'opened':True})
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/reference-preview')
|
||||
async def preview(request):
|
||||
access.browser(request);data=await request.json()
|
||||
from PIL import Image,ImageOps
|
||||
def prepare():
|
||||
source=Path(folder_paths.get_annotated_filepath(data['file'])).resolve()
|
||||
if not source.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Reference esterna a input.')
|
||||
rgba=ImageOps.exif_transpose(Image.open(source)).convert('RGBA');mask=ImageOps.invert(rgba.getchannel('A'))
|
||||
settings=data['settings']
|
||||
sam_file=None
|
||||
if settings.get('source')=='prompt' and settings.get('mask'):
|
||||
mask,sam_file=prompt_mask(source,rgba,settings)
|
||||
elif settings.get('maskFile'):
|
||||
mask_path=Path(folder_paths.get_annotated_filepath(settings['maskFile'])).resolve()
|
||||
if not mask_path.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Maschera esterna a input.')
|
||||
mask=Image.open(mask_path).convert('L')
|
||||
result,_=process_reference(rgba,mask,settings)
|
||||
directory=Path(folder_paths.get_input_directory())/'DOGMA_API'/'previews';directory.mkdir(parents=True,exist_ok=True)
|
||||
filename='ref_'+uuid.uuid4().hex+'.png';result.save(directory/filename)
|
||||
response={'file':'DOGMA_API/previews/'+filename,'width':result.width,'height':result.height}
|
||||
if sam_file:response.update(maskFile=sam_file,samSource=data['file'],samPrompt=settings['prompt'],samSegment=int(settings.get('segment') or 0),emptyMask=not bool(mask.getbbox()))
|
||||
return response
|
||||
try:return web.json_response(await asyncio.to_thread(prepare))
|
||||
except (ValueError,OSError,KeyError,RuntimeError,ImportError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS={'DOGMAAPIReferenceV2':DOGMAAPIReferenceV2,'DOGMAAPIImageOutputV2':DOGMAAPIImageOutputV2,'DOGMAAPIVideoOutputV2':DOGMAAPIVideoOutputV2}
|
||||
NODE_DISPLAY_NAME_MAPPINGS={'DOGMAAPIReferenceV2':'DOGMA / Reference preparation','DOGMAAPIImageOutputV2':'DOGMA / Image output','DOGMAAPIVideoOutputV2':'DOGMA / Video output'}
|
||||
@@ -13,9 +13,10 @@ def versioned_urls(urls, extension_dirs, web_directory):
|
||||
result = []
|
||||
for url in urls:
|
||||
parts = urlsplit(url)
|
||||
# This package has one entry module. Do not rewrite third-party URLs.
|
||||
if any(parts.path == prefix + "dogma_categories.js" for prefix in prefixes):
|
||||
digest = hashlib.sha256((root / "dogma_categories.js").read_bytes()).hexdigest()[:20]
|
||||
# Version only this package's own entry modules. Do not rewrite third-party URLs.
|
||||
entry = parts.path.rsplit("/", 1)[-1]
|
||||
if entry in ("dogma_categories.js", "dogma_api_platform.js") and any(parts.path == prefix + entry for prefix in prefixes):
|
||||
digest = hashlib.sha256((root / entry).read_bytes()).hexdigest()[:20]
|
||||
query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
|
||||
if k != "dogma_build"]
|
||||
query.append(("dogma_build", digest))
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-dogma-nodes"
|
||||
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
|
||||
version = "1.0.52"
|
||||
version = "1.0.56"
|
||||
license = { file = "LICENSE" }
|
||||
dependencies = ["scipy>=1.10"]
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,127 @@
|
||||
export const copy=x=>JSON.parse(JSON.stringify(x));
|
||||
export const FAMILIES=[
|
||||
{key:'nano',name:'Nanobanana',short:'NB',type:'GeminiImage2Node'},
|
||||
{key:'gpt',name:'GPT Image',short:'GPT',type:'OpenAIGPTImageNodeV2'},
|
||||
{key:'flux',name:'Flux 3',short:'F3',type:'Flux3ImageNode'},
|
||||
{key:'seedream',name:'Seedream',short:'SD',type:'ByteDanceSeedreamNodeV3'},
|
||||
];
|
||||
export const VIDEO_FAMILIES=[{key:'seedance',name:'Seedance',short:'V',type:'ByteDance2ReferenceNodeV2'}];
|
||||
export const ALL_FAMILIES=[...FAMILIES,...VIDEO_FAMILIES];
|
||||
export const families=s=>s.mode==='video'?VIDEO_FAMILIES:FAMILIES;
|
||||
export const safeName=s=>String(s||'').trim().replace(/[^\p{L}\p{N}_.-]+/gu,'_').replace(/^\.+/,'').slice(0,100);
|
||||
export function inputSpec(def,values,name){
|
||||
const parts=name.split('.');let inputs=def?.input;
|
||||
for(let i=0;i<parts.length;i++){
|
||||
const spec=inputs?.required?.[parts[i]]||inputs?.optional?.[parts[i]];if(!spec)return null;
|
||||
if(i===parts.length-1)return spec;
|
||||
if(spec[0]==='COMFY_DYNAMICCOMBO_V3'){const key=values[parts.slice(0,i+1).join('.')];inputs=spec[1].options.find(o=>o.key===key)?.inputs;}else return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export function viewParameters(file){
|
||||
if(typeof file!=='string')return {filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'};
|
||||
const parts=file.replaceAll('\\','/').split('/');return {filename:parts.pop(),subfolder:parts.join('/'),type:'input'};
|
||||
}
|
||||
export function choicesFor(spec){if(!spec)return null;if(Array.isArray(spec[0]))return spec[0];if(spec[0]==='COMBO')return spec[1].options;if(spec[0]==='COMFY_DYNAMICCOMBO_V3')return spec[1].options.map(o=>o.key);return null;}
|
||||
export function parameterSpecs(def,values){
|
||||
const result={};const walk=(inputs,prefix='')=>{for(const [key,spec] of Object.entries({...inputs?.required,...inputs?.optional})){
|
||||
const name=prefix+key;const choices=choicesFor(spec);
|
||||
if(choices||['INT','FLOAT','BOOLEAN','STRING'].includes(spec[0]))result[name]=spec;
|
||||
if(spec[0]==='COMFY_DYNAMICCOMBO_V3')walk(spec[1].options.find(o=>o.key===values[name])?.inputs,name+'.');
|
||||
}};walk(def?.input);return result;
|
||||
}
|
||||
export function modelValues(def,values){
|
||||
const specs=parameterSpecs(def,values),next={};for(const [key,spec] of Object.entries(specs)){
|
||||
const choices=choicesFor(spec),value=values[key];next[key]=value!==undefined&&(!choices||choices.includes(value))?value:spec[1]?.default??choices?.[0]??(spec[0]==='BOOLEAN'?false:spec[0]==='STRING'?'':0);
|
||||
}return next;
|
||||
}
|
||||
export function sortedChoices(key,values){
|
||||
const list=[...new Set(values.map(String))];if(!/resolution|size_preset|size$/.test(key))return list;
|
||||
const score=v=>{if(key==='model.size_preset'){const tier=v.match(/([\d.]+)K/i);return tier?+tier[1]:Infinity;}const dims=v.match(/(\d+)x(\d+)/);if(dims)return +dims[1]*+dims[2];const k=v.match(/([\d.]+)\s*[kK]/);if(k)return +k[1]*1000;const p=v.match(/(\d+)p/i);if(p)return +p[1];return Infinity;};return list.sort((a,b)=>score(a)-score(b));
|
||||
}
|
||||
export function todayCode(){const parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Rome',day:'2-digit',month:'2-digit',year:'2-digit'}).formatToParts(new Date());return ['day','month','year'].map(k=>parts.find(p=>p.type===k).value).join('');}
|
||||
export function titleParts(s){return [s.project,s.scene,s.filename||'DOGMA',s.appendDate?(s.dateMode==='today'?todayCode():s.date||todayCode()):''].map(safeName).filter(Boolean);}
|
||||
export function prefix(s,f){return ['DOGMA/API',safeName(s.project),safeName(s.scene),titleParts(s).join('_')+'_'+f.short].filter(Boolean).join('/');}
|
||||
export function migrateState(raw){
|
||||
const s=copy(raw);s.schema=4;s.session ||= crypto.randomUUID();s.prompts ||= {image:s.prompt||'',video:''};s.mode ||= 'image';s.imageEdit ??= true;s.appendDate ??= false;s.date ||= todayCode();s.runCount ||= 1;
|
||||
s.dateMode ||= raw.schema===1?'manual':'today';if(s.dateMode==='today')s.date=todayCode();
|
||||
s.workspace ||= '';s.library ||= [];s.results ||= [];s.references ||= [];s.filters ||= {models:[],project:'*',scene:'*',kind:'all',workspace:'*'};s.density ??= 45;s.workExpanded ??= false;
|
||||
for(const m of Object.values(s.models||{})){m.parameters ||= m.variants?.[0]||{};delete m.variants;delete m.editVariant;delete m.seedMode;}
|
||||
s.filters.hideErrors ??= false;
|
||||
for(const [i,r] of s.references.entries()){r.kind ||= 'image';r.role ||= 'reference';const legacyMask=raw.schema===1&&i===0&&!!raw.maskEnabled;r.process ||= {enabled:legacyMask,mask:legacyMask,maskMode:'edit',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:false,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:'#ff00ff'};}
|
||||
if(raw.schema<3)for(const r of [...s.references])if(r.kind==='image'&&r.modes?.includes('video')&&['first','last'].includes(r.role))s.references.push({...copy(r),role:'reference'});
|
||||
for(const r of s.results)r.kind ||= 'image';
|
||||
return s;
|
||||
}
|
||||
export function plannedJobs(s){const repeats=Number(s.runCount??1);if(!Number.isInteger(repeats)||repeats<1||repeats>64)throw new Error('Run deve essere da 1 a 64.');const counts={};return Array.from({length:repeats},(_,repeat)=>families(s).flatMap(f=>{const m=s.models[f.key];if(!m?.enabled)return[];const n=Number(m.quantity);if(!Number.isInteger(n)||n<1||n>64)throw new Error('Quantity deve essere da 1 a 64.');return Array.from({length:n},()=>({family:f.key,index:(counts[f.key]=(counts[f.key]||0)+1)-1,repeat,kind:s.mode==='video'?'video':'image'}));})).flat();}
|
||||
export const preparedMask=ref=>!!ref.process?.maskFile&&ref.process.samSource===ref.file&&ref.process.samPrompt===ref.process.prompt&&Number(ref.process.samSegment)===Number(ref.process.segment||0);
|
||||
export function visibleReferences(s){return s.references.filter(r=>(!r.modes||r.modes.includes(s.mode))&&(s.mode==='video'?(s.models.seedance?.engine==='frames'?r.kind==='image'&&['first','last'].includes(r.role):r.role!=='first'&&r.role!=='last'):r.kind!=='video'));}
|
||||
export function activeReferences(s){return visibleReferences(s).filter(r=>r.enabled);}
|
||||
export function validateState(s){
|
||||
if(!s.prompts[s.mode]?.trim())throw new Error('Scrivi un prompt.');
|
||||
if(!plannedJobs(s).length)throw new Error('Attiva almeno un modello.');
|
||||
const refs=activeReferences(s),imgs=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
|
||||
if(refs.some(r=>!r.file))throw new Error('Ricarica le reference mancanti.');
|
||||
if(s.mode==='image'){
|
||||
if(s.imageEdit&&!imgs.length)throw new Error('Image Edit richiede Image 1.');
|
||||
const limits={nano:14,gpt:16,flux:10,seedream:10},max=Math.min(...FAMILIES.filter(f=>s.models[f.key]?.enabled).map(f=>limits[f.key]));if(imgs.length>max)throw new Error(`I modelli attivi supportano fino a ${max} reference.`);
|
||||
}else {
|
||||
const m=s.models.seedance;
|
||||
if(m.engine==='frames'&&imgs.length>2)throw new Error('Usa al massimo un First frame e un Last frame.');
|
||||
if(m.engine==='frames'&&['first','last'].some(role=>imgs.filter(r=>r.role===role).length>1))throw new Error('Assegna un solo First frame e un solo Last frame.');
|
||||
if(m.engine==='frames'&&!imgs.length)throw new Error('Aggiungi almeno un frame immagine.');
|
||||
if(m.engine!=='frames'&&!refs.length)throw new Error('Aggiungi una reference immagine o video.');
|
||||
const p=m.engine==='frames'?m.frames:m.parameters;
|
||||
if(m.engine!=='frames'&&['edit','extend'].includes(p['model.task_type'])&&!videos.length)throw new Error('Video Edit ed Extend richiedono un video sorgente.');
|
||||
if(imgs.length>30||videos.length>10)throw new Error('Troppe reference per Seedance 2.5.');
|
||||
}
|
||||
for(const f of families(s)){
|
||||
const m=s.models[f.key];if(!m.enabled)continue;const p=m.engine==='frames'?m.frames:m.parameters;
|
||||
for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
|
||||
const n=Number(v),min=f.key==='gpt'?480:240,max=f.key==='gpt'?3840:8594,step=f.key==='gpt'?16:2;
|
||||
if(!Number.isInteger(n)||n<min||n>max||n%step)throw new Error(`${f.name}: dimensioni da ${min} a ${max}, multiple di ${step}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
export function compileBatch(s,jobs,baseSeed){
|
||||
validateState(s);const output={},refs=activeReferences(s),images=[],videos=[];
|
||||
refs.forEach((ref,i)=>{
|
||||
const id=String(9000+i*10);output[id]={class_type:ref.kind==='video'?'LoadVideo':'LoadImage',inputs:{[ref.kind==='video'?'file':'image']:ref.file}};
|
||||
if(ref.kind==='video'){videos.push({ref,link:[id,0]});return;}
|
||||
let link=[id,0];const p=ref.process;
|
||||
if(p?.enabled){
|
||||
let mask=[id,1];
|
||||
if(p.maskFile){const mid=String(9001+i*10);output[mid]={class_type:'LoadImage',inputs:{image:p.maskFile}};const tid=String(9002+i*10);output[tid]={class_type:'ImageToMask',inputs:{image:[mid,0],channel:'red'}};mask=[tid,0];}
|
||||
if(p.source==='prompt'&&p.mask&&!preparedMask(ref)){const sid=String(9003+i*10);output[sid]={class_type:'SAM3Segment',inputs:{image:[id,0],prompt:p.prompt,output_mode:'Merged',confidence_threshold:.5,max_segments:0,segment_pick:Number(p.segment||0),mask_blur:0,mask_offset:0,device:'Auto',invert_output:false,unload_model:false,background:'Alpha',background_color:'#222222'}};mask=[sid,1];}
|
||||
const pid=String(9004+i*10);output[pid]={class_type:'DOGMAAPIReferenceV2',inputs:{image:[id,0],mask,settings:JSON.stringify(p)}};link=[pid,0];
|
||||
}
|
||||
images.push({ref,link});
|
||||
});
|
||||
let nanoBatch=null;
|
||||
if(s.mode==='image'&&s.models.nano?.enabled&&images.length){nanoBatch=images[0].link;images.slice(1).forEach((img,i)=>{const id=String(9800+i);output[id]={class_type:'ImageBatch',inputs:{image1:nanoBatch,image2:img.link}};nanoBatch=[id,0];});}
|
||||
jobs.forEach((job,i)=>{
|
||||
const f=ALL_FAMILIES.find(f=>f.key===job.family),m=s.models[f.key],inputs=copy(m.engine==='frames'?m.frames:m.parameters);
|
||||
for(const k of Object.keys(inputs))if(k.startsWith('control_after_generate')||k==='n')delete inputs[k];
|
||||
const seed=(Number(baseSeed)+i)%2147483647;inputs[f.key==='seedream'?'model.seed':'seed']=seed;
|
||||
const prompt=s.prompts[s.mode];inputs[s.mode==='video'?'model.prompt':'prompt']=prompt;
|
||||
let type=f.type;
|
||||
if(s.mode==='video'){
|
||||
if(m.engine==='frames'){
|
||||
type='ByteDance2FirstLastFrameNode';
|
||||
const first=images.find(x=>x.ref.role==='first')||images.find(x=>x.ref.role!=='last');const last=images.find(x=>x.ref.role==='last')||images.filter(x=>x!==first)[0];
|
||||
if(first)inputs.first_frame=first.link;if(last)inputs.last_frame=last.link;
|
||||
}else{images.forEach((x,j)=>inputs[`model.reference_images.image_${j+1}`]=x.link);videos.forEach((x,j)=>inputs[`model.reference_videos.video_${j+1}`]=x.link);}
|
||||
}else if(f.key==='nano'){if(nanoBatch)inputs.images=nanoBatch;}
|
||||
else{if(f.key==='gpt')inputs.n=1;images.forEach((x,j)=>inputs[`${f.key==='flux'?'':'model.'}images.image_${j+1}`]=x.link);}
|
||||
const gen=String(10000+i*10),save=String(10001+i*10);
|
||||
Object.assign(job,{seed,generator:gen,output:save,project:s.project||'',scene:s.scene||'',workspace:s.workspace||'',filename:titleParts(s).join('_'),imageEdit:s.mode==='image'&&s.imageEdit,baseReference:s.mode==='image'&&s.imageEdit&&images.length?copy(images[0].ref):null,prompt,parameters:copy(inputs)});
|
||||
if(job.baseReference)delete job.baseReference.editorDraft;
|
||||
output[gen]={class_type:type,inputs,_meta:{title:`${f.name} ${job.index+1}`}};
|
||||
const metadata={...copy(job),session:s.session,prefix:prefix(s,f),date:s.dateMode==='today'?todayCode():s.date,appendDate:s.appendDate};delete metadata.images;delete metadata.parameters;
|
||||
output[save]={class_type:s.mode==='video'?'DOGMAAPIVideoOutputV2':'DOGMAAPIImageOutputV2',inputs:{[s.mode==='video'?'video':'images']:[gen,0],metadata:JSON.stringify(metadata)}};
|
||||
});
|
||||
return {output,jobs};
|
||||
}
|
||||
export function orderResults(results){const groups=new Map();for(const r of results){const key=r.batch||r.id;groups.set(key,Math.max(groups.get(key)||0,r.batchStarted||r.started||r.finished||0));}return [...results].sort((a,b)=>{const ga=a.batch||a.id,gb=b.batch||b.id;return groups.get(gb)-groups.get(ga)||(ga===gb?(a.ordinal??a.index??0)-(b.ordinal??b.index??0):String(gb).localeCompare(String(ga)))||String(a.id).localeCompare(String(b.id));});}
|
||||
export function filterResults(results,filters,now=Date.now()){return results.filter(r=>(!filters.models?.length||filters.models.includes(r.family))&&(filters.project==='*'||(r.project||'')===filters.project)&&(filters.scene==='*'||(r.scene||'')===filters.scene)&&(filters.workspace==='*'||(r.workspace||'')===filters.workspace)&&(filters.kind==='all'||r.kind===filters.kind)&&(!filters.hideErrors||!['failed','missing'].includes(r.status)||(r.errorVisibleUntil||0)>now));}
|
||||
export function savedFilename(job,index=0){return job.exported?.[index]?.split(/[\\/]/).at(-1)||job.images?.[index]?.filename||job.filename||'';}
|
||||
@@ -0,0 +1,113 @@
|
||||
{
|
||||
"schema": 4,
|
||||
"runCount": 1,
|
||||
"session": "",
|
||||
"mode": "image",
|
||||
"imageEdit": true,
|
||||
"project": "",
|
||||
"scene": "",
|
||||
"filename": "DOGMA",
|
||||
"date": "",
|
||||
"appendDate": false,
|
||||
"workspace": "",
|
||||
"prompts": {
|
||||
"image": "",
|
||||
"video": ""
|
||||
},
|
||||
"density": 55,
|
||||
"models": {
|
||||
"nano": {
|
||||
"enabled": true,
|
||||
"expanded": false,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"model": "gemini-3-pro-image-preview",
|
||||
"seed": 637339876168947,
|
||||
"aspect_ratio": "16:9",
|
||||
"resolution": "2K",
|
||||
"response_modalities": "IMAGE",
|
||||
"system_prompt": "Follow the user prompt and the assigned roles of the reference images precisely."
|
||||
}
|
||||
},
|
||||
"gpt": {
|
||||
"enabled": true,
|
||||
"expanded": false,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"model": "gpt-image-2",
|
||||
"model.size": "2048x1152",
|
||||
"model.custom_width": 1920,
|
||||
"model.custom_height": 1088,
|
||||
"model.background": "auto",
|
||||
"model.quality": "high",
|
||||
"n": 1,
|
||||
"seed": 726834962
|
||||
}
|
||||
},
|
||||
"flux": {
|
||||
"enabled": true,
|
||||
"expanded": false,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"aspect_ratio": "auto",
|
||||
"resolution": "2K",
|
||||
"grounding": true,
|
||||
"safety_tolerance": 4,
|
||||
"seed": 390115469
|
||||
}
|
||||
},
|
||||
"seedream": {
|
||||
"enabled": true,
|
||||
"expanded": true,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"model": "seedream 5.5",
|
||||
"model.size_preset": "Custom",
|
||||
"model.width": 2048,
|
||||
"model.height": 1152,
|
||||
"model.background": "auto",
|
||||
"model.seed": 42,
|
||||
"model.watermark": false
|
||||
}
|
||||
},
|
||||
"seedance": {
|
||||
"enabled": true,
|
||||
"expanded": true,
|
||||
"quantity": 1,
|
||||
"engine": "reference",
|
||||
"parameters": {
|
||||
"model": "Seedance 2.5",
|
||||
"model.resolution": "1080p",
|
||||
"model.ratio": "adaptive",
|
||||
"model.duration": 15,
|
||||
"model.generate_audio": false,
|
||||
"model.task_type": "edit",
|
||||
"model.output_format": "mp4",
|
||||
"model.auto_downscale": false,
|
||||
"model.auto_upscale": false,
|
||||
"seed": 1982892718,
|
||||
"watermark": false
|
||||
},
|
||||
"frames": {
|
||||
"model": "Seedance 2.5",
|
||||
"model.resolution": "720p",
|
||||
"model.duration": 4,
|
||||
"model.generate_audio": false,
|
||||
"model.output_format": "mp4",
|
||||
"seed": 1439633762,
|
||||
"watermark": false,
|
||||
"first_frame_asset_id": "",
|
||||
"last_frame_asset_id": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"references": [],
|
||||
"results": [],
|
||||
"filters": {
|
||||
"models": [],
|
||||
"project": "*",
|
||||
"scene": "*",
|
||||
"kind": "all",
|
||||
"workspace": "*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export function icon(name){
|
||||
const ns='http://www.w3.org/2000/svg',s=document.createElementNS(ns,'svg');s.setAttribute('viewBox','0 0 24 24');s.setAttribute('aria-hidden','true');s.classList.add('dap-icon');
|
||||
const paths={
|
||||
prompt:[['path',{d:'M4 3h16v18H4zM7 7h10M7 11h10M7 15h7'}]],
|
||||
copy:[['rect',{x:8,y:8,width:13,height:13,rx:1}],['path',{d:'M16 8V3H3v13h5'}]],
|
||||
image:[['rect',{x:3,y:3,width:18,height:18,rx:2}],['circle',{cx:8,cy:8,r:1.1,fill:'currentColor'}],['path',{d:'M3 17l6-6 4 3 8-8'}]],
|
||||
media:[['path',{d:'M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v5M3 17l6-6 3 3'}],['circle',{cx:8,cy:8,r:1.1,fill:'currentColor'}],['path',{d:'m15 12 7 4.5-7 4.5z'}]],
|
||||
video:[['rect',{x:3,y:3,width:18,height:18,rx:1}],['path',{d:'M3 7h18M3 17h18M7 3v4m5-4v4m5-4v4M7 17v4m5-4v4m5-4v4'}]],
|
||||
chevron:[['path',{d:'m7 10 5 5 5-5'}]],
|
||||
lines:[['path',{d:'M8 9h8M8 12h8M8 15h8'}]],
|
||||
single:[['rect',{x:3,y:4,width:18,height:16,rx:.6}]],
|
||||
grid:[['path',{d:'M2 4h5v6H2zM10 4h5v6h-5zM18 4h5v6h-5zM2 14h5v6H2zM10 14h5v6h-5zM18 14h5v6h-5z'}]],
|
||||
compare:[['path',{d:'M1 6a1 1 0 0 1 1-1h20a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1Z M1.5 6v11a.5.5 0 0 0 .5.5h9V5.5H2a.5.5 0 0 0-.5.5Z M13.2 6.3v10.4h4.1c4 0 4.8-4.5 1.6-5.3 2.5-1.1 1.8-5.1-1.6-5.1Z M14.6 7.6h2.6c2.4 0 2.4 3.1 0 3.1h-2.6Z M14.6 12h2.8c2.7 0 2.7 3.4 0 3.4h-2.8Z M2.6 16.7 6.3 6.3h1.5l3.7 10.4H10l-1-3H5l-1 3Z M5.5 12.4h3L7 8Z',fill:'currentColor',stroke:'none','fill-rule':'evenodd'}]],
|
||||
play:[['path',{d:'M7 3l15 9L7 21z',fill:'currentColor',stroke:'none'}]],
|
||||
plus:[['path',{d:'M12 4v16M4 12h16'}]],
|
||||
close:[['path',{d:'m6 6 12 12M18 6 6 18'}]],
|
||||
folder:[['path',{d:'M2 6h8l2 3h10l-2 11H3zM2 6V4h8l2 2h8v3'}]],
|
||||
external:[['path',{d:'M14 3h7v7M21 3 11 13M10 5H4v15h15v-6'}]],
|
||||
download:[['path',{d:'M12 3v12m-5-5 5 5 5-5M4 17v4h16v-4'}]],
|
||||
edit:[['path',{d:'m4 16 12-12 4 4L8 20H4zm10-10 4 4M4 20h16'}]],
|
||||
zoomIn:[['circle',{cx:10,cy:10,r:7}],['path',{d:'m15 15 7 7M6 10h8M10 6v8'}]],
|
||||
zoomOut:[['circle',{cx:10,cy:10,r:7}],['path',{d:'m15 15 7 7M6 10h8'}]],
|
||||
fit:[['path',{d:'M3 9V3h6m6 0h6v6M3 15v6h6m6 0h6v-6'}]],
|
||||
refresh:[['path',{d:'M20 8a9 9 0 1 0 0 9M20 3v6h-6'}]],
|
||||
filter:[['path',{d:'M3 5h18l-7 8v7l-4-2v-5z'}]],
|
||||
arrow:[['path',{d:'m14 5-7 7 7 7'}]],
|
||||
};
|
||||
for(const [tag,attributes] of paths[name]||paths.plus){const p=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attributes))p.setAttribute(k,String(v));s.append(p);}
|
||||
return s;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.3 KiB |
@@ -0,0 +1,186 @@
|
||||
@font-face{font-family:'Roboto Mono';src:url('./dogma_api_assets/RobotoMono-Variable.ttf') format('truetype');font-weight:100 700;font-style:normal;font-display:swap}
|
||||
.dap,.dap-modal{--orange:#ff6626;--line:#292929;--muted:#777;--ink:#d4d4d4;box-sizing:border-box;background:#000;color:var(--ink);font-family:Arial,Helvetica,sans-serif;font-size:13px;color-scheme:dark}
|
||||
.dap *,.dap-modal *{box-sizing:border-box}.dap [hidden],.dap-modal [hidden]{display:none!important}.dap button,.dap input,.dap select,.dap textarea,.dap-modal button,.dap-modal input,.dap-modal select,.dap-modal textarea{font:inherit;color:inherit}.dap button,.dap-modal button{cursor:pointer}.dap button:disabled,.dap-modal button:disabled{opacity:.35;cursor:default}.dap-icon{display:block;width:19px;height:19px;flex:none;fill:none;stroke:currentColor;stroke-width:1.35;stroke-linecap:round;stroke-linejoin:round;pointer-events:none}
|
||||
.dap button,.dap summary,.dap select,.dap input,.dap textarea,.dap-modal button,.dap-modal summary,.dap-modal input,.dap-modal select{transition:color .15s,border-color .15s,background-color .15s,box-shadow .15s,filter .15s}.dap button:hover:not(:disabled),.dap summary:hover,.dap-modal button:hover:not(:disabled),.dap-modal summary:hover{color:var(--orange);border-color:#9d4826}.dap button:active:not(:disabled),.dap-modal button:active:not(:disabled){filter:brightness(1.2)}.dap input:hover,.dap select:hover,.dap textarea:hover,.dap-modal input:hover,.dap-modal select:hover{border-color:#9d4826}.dap input:focus,.dap textarea:focus,.dap select:focus,.dap-modal input:focus,.dap-modal select:focus{outline:none;color:#fff}.dap button:focus-visible,.dap summary:focus-visible,.dap input:focus-visible,.dap select:focus-visible,.dap textarea:focus-visible,.dap-modal button:focus-visible,.dap-modal input:focus-visible,.dap-modal select:focus-visible{outline:1px solid var(--orange);outline-offset:3px}
|
||||
.dap{position:fixed;inset:0;width:100vw;height:100dvh;max-width:none;max-height:none;margin:0;border:0;padding:0;overflow:hidden}.dap::backdrop,.dap-modal::backdrop{background:#000c}.dap-header{height:142px;display:flex;justify-content:space-between;align-items:flex-start;padding:18px 22px 0;gap:20px}.dap-brand{display:flex;align-items:flex-end;gap:8px;white-space:nowrap}.dap-brand img{width:163px;height:34px;object-fit:contain}.dap-brand>span{font:16px/1 'Roboto Mono',monospace;color:var(--orange);transform:translateY(3px)}.dap-actions{display:flex;align-items:center;gap:14px}.dap-credit{border:0;background:none;color:#777;font:10px 'Roboto Mono',monospace!important;padding:7px}.dap-credit:hover{color:#aaa!important}.dap-run{display:flex;align-items:center;justify-content:space-between;gap:25px;min-width:144px;height:28px;padding:4px 12px;border:1px solid var(--orange);border-radius:30px;background:var(--orange);color:#000!important;font-weight:bold!important}.dap-run .dap-icon{height:18px;width:18px}.dap-run:hover:not(:disabled){background:#ff813f!important;border-color:#ff813f!important;box-shadow:none}.dap-icon-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;background:transparent;border:1px solid transparent;padding:4px;color:#888}.dap-icon-button:hover{color:var(--orange)}
|
||||
.dap-layout{height:calc(100dvh - 142px);display:grid;grid-template-columns:minmax(320px,24.25%) minmax(0,1fr);padding:0 10px;min-height:0;overflow:hidden}.dap-side{height:100%;min-height:0;min-width:0;overflow-y:auto;overflow-x:hidden;border-right:1px solid #191919;padding:0 12px 32px 0;scrollbar-width:thin;scrollbar-color:#393939 #000;overscroll-behavior:contain}.dap-tabs{display:flex;gap:12px;min-height:30px;margin-bottom:11px}.dap-tabs button{display:flex;align-items:center;gap:8px;flex:1;min-width:0;height:29px;padding:3px 12px;border:1px solid #602c17;border-radius:30px;background:none;color:#804121;text-align:left}.dap-tabs button .dap-icon{width:15px;height:15px;stroke-width:1.5}.dap-tabs button.active{color:var(--orange);border-color:var(--orange)}.dap-tabs button:hover{background:#ff662608}.dap-edit-mode{display:flex;align-items:center;gap:10px;padding:0 12px 0;min-height:29px;margin-bottom:24px;color:#aaa;font-size:11px}.dap-edit-mode small{margin-left:auto;font:9px 'Roboto Mono',monospace;color:#666}.dap-controls{padding-left:12px;overflow:visible;min-width:0}.dap-section{margin-bottom:28px}.dap-label{font:10px 'Roboto Mono',monospace;color:#7a7a7a;margin:0 0 11px;letter-spacing:.03em}
|
||||
.dap-refs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;min-width:0}.dap-ref,.dap-add{position:relative;min-width:0;border:1px solid #272727;border-radius:13px;overflow:hidden;aspect-ratio:1.65;background:#040404}.dap-ref>img,.dap-ref>video{width:100%;height:100%;object-fit:cover;display:block;cursor:crosshair;transition:filter .18s}.dap-ref:hover>img,.dap-ref:hover>video{filter:brightness(1.08)}.dap-ref.disabled>img,.dap-ref.disabled>video{opacity:.23}.dap-ref-order{position:absolute;top:8px;left:8px;font:8px 'Roboto Mono',monospace;color:#eee;text-shadow:0 1px 3px #000;pointer-events:none}.dap-ref-edited{position:absolute;top:8px;right:8px;font:8px 'Roboto Mono',monospace;color:var(--orange)}.dap-ref-tools{position:absolute;bottom:0;left:0;right:0;display:flex;align-items:center;justify-content:flex-end;gap:4px;padding:17px 5px 5px;background:linear-gradient(transparent,#000d)}.dap-ref-tools .dap-icon-button{padding:2px;color:#e5784b}.dap-ref-tools .dap-icon{width:14px;height:14px}.dap-ref-role{position:absolute;left:5px;right:5px;top:25px;width:calc(100% - 10px);background:#000a;border:1px solid #444;border-radius:10px;font:8px 'Roboto Mono',monospace!important;padding:2px 4px}.dap-ref.missing:after{content:'RICARICA FILE';position:absolute;top:44%;left:0;right:0;text-align:center;color:var(--orange);font:9px 'Roboto Mono',monospace;pointer-events:none}.dap-add{display:flex;flex-direction:column;gap:7px;justify-content:center;align-items:center;color:#555;padding:12px}.dap-add .dap-icon{width:24px;height:24px;stroke-width:.6}.dap-add span{font:8px 'Roboto Mono',monospace}
|
||||
.dap-prompt-wrap{position:relative}.dap textarea{display:block;width:100%;min-height:105px;max-height:none;resize:none;border:1px solid #282828;border-radius:14px;background:#000;padding:9px 10px;font:12px/1.4 Arial,Helvetica,sans-serif;scrollbar-width:thin;scrollbar-color:#393939 #000}.dap textarea:hover{border-color:#68402a}.dap textarea:focus{border-color:#a84b23}.dap-resize-handle{position:absolute;bottom:5px;right:6px;width:12px;height:12px;cursor:ns-resize;background:repeating-linear-gradient(135deg,transparent 0 3px,#777 3px 4px,transparent 4px 6px);clip-path:polygon(100% 0,100% 100%,0 100%);opacity:.65;touch-action:none}.dap-resize-handle:hover{opacity:1;filter:brightness(1.2)}
|
||||
.dap-field{position:relative;display:flex;align-items:center;gap:7px;min-height:28px;margin-bottom:8px;padding:3px 11px;border:1px solid #252525;border-radius:25px;min-width:0;font:10px 'Roboto Mono',monospace;transition:border-color .15s,background .15s}.dap-field:hover{border-color:#5a3929;background:#ff662604}.dap-field:focus-within{border-color:#8c421f}.dap-field>span{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#777;font-size:9px}.dap-field input,.dap-field select{min-width:0;max-width:64%;padding:0;border:0;background:transparent;color:#d1d1d1;text-align:right;font:10px 'Roboto Mono',monospace;outline:none}.dap-field input[type=text]{width:65%}.dap-field input[type=number]{width:95px;appearance:textfield;-moz-appearance:textfield}.dap-field input[type=number]::-webkit-inner-spin-button{display:none}.dap-field input[type=color]{height:18px;width:35px;padding:0;border-radius:5px;cursor:pointer}.dap-field select{appearance:none;padding-right:16px;cursor:pointer}.dap-field.has-select>.dap-icon{position:absolute;right:8px;width:11px;height:11px;color:#aaa}.dap-field input[readonly]{color:#aaa;cursor:default}.dap-field input::placeholder{color:#494949}.dap-field select option{background:#080808;color:#ddd}.dap-field-hint{font:9px/1.5 'Roboto Mono',monospace;color:#666;margin:0 7px 10px}.dap-date-row{display:flex;align-items:center;gap:10px;margin:10px 0 12px;font:10px 'Roboto Mono',monospace;color:#999}.dap-date-row small{margin-left:auto;color:#805339}.dap-workspace-button{display:flex;width:100%;border:1px solid #303030;border-radius:20px;padding:7px 10px;text-align:left;justify-content:flex-start;color:#aaa}.dap-workspace-button .dap-icon{width:16px;height:16px;color:var(--orange)}.dap-workspace-button span{min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font:10px 'Roboto Mono',monospace}.dap-filename-preview{font:9px/1.5 'Roboto Mono',monospace;color:#76513d;overflow-wrap:anywhere;padding:9px 7px 0}
|
||||
.dap-model{margin-bottom:8px}.dap-model-head{display:flex;align-items:flex-start;gap:7px;min-width:0}.dap-model details{flex:1;min-width:0}.dap summary{list-style:none;cursor:pointer}.dap summary::-webkit-details-marker{display:none}.dap-model summary{display:flex;align-items:center;gap:10px;min-height:27px;max-width:100%;padding:4px 10px 4px 11px;border:1px solid #292929;border-radius:22px;color:#999}.dap-model.enabled summary{color:var(--orange)}.dap-model summary>span{white-space:nowrap}.dap-model summary>small{font:8px 'Roboto Mono',monospace;color:#676767;min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.dap-model summary>.dap-icon{margin-left:auto;height:13px;width:13px;color:var(--orange);transform:rotate(0);transition:transform .16s}.dap-model details[open]>summary>.dap-icon{transform:rotate(180deg)}.dap-model summary:hover{background:#ff662607}.dap-model-body{padding:10px 0 3px}.dap-advanced summary{font:9px 'Roboto Mono',monospace;border:0;border-radius:0;color:#777!important;padding:7px}.dap-advanced textarea{height:170px;font-size:11px}
|
||||
.dap-main{min-width:0;min-height:0;display:flex;flex-direction:column;height:100%;padding:0 10px 0 17px;overflow:hidden}.dap-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;min-height:30px;margin-bottom:12px;flex-shrink:0}.dap-project{font-size:13px;color:#995330;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.dap-views{display:flex;align-items:center;gap:18px}.dap-views .dap-icon{height:21px;width:21px}.dap-views .active{color:var(--orange)}.dap-views input[type=range]{width:180px;appearance:none;background:#272727;height:1px;outline:none;cursor:ew-resize}.dap-views input[type=range]::-webkit-slider-thumb{appearance:none;width:24px;height:24px;border:1px solid var(--orange);border-radius:50%;background:#000;transition:background .15s,box-shadow .15s;cursor:ew-resize}.dap-views input[type=range]:hover::-webkit-slider-thumb{background:#1b0c05;box-shadow:none}.dap-filters{display:flex;align-items:center;justify-content:flex-end;gap:10px;min-height:28px;flex-shrink:0;margin-bottom:9px;flex-wrap:wrap}.dap-filter,.dap-filter-models>summary{display:flex;align-items:center;gap:8px;position:relative;border:1px solid #282828;border-radius:20px;min-height:25px;padding:3px 9px;font:9px 'Roboto Mono',monospace;color:#888}.dap-filter:hover,.dap-filter-models>summary:hover{border-color:#7b3a20}.dap-filter>span{font-size:8px;color:#555}.dap-filter select{max-width:160px;min-width:65px;border:0;background:none;appearance:none;padding-right:14px;color:#aaa;outline:0;cursor:pointer;font:9px 'Roboto Mono',monospace}.dap-filter>.dap-icon{width:10px;height:10px;position:absolute;right:7px}.dap-filter select option{background:#080808}.dap-filter-models{position:relative}.dap-filter-models>summary>.dap-icon{width:11px;height:11px}.dap-filter-models>summary>span{max-width:260px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.dap-filter-menu{position:absolute;top:31px;right:0;z-index:20;min-width:210px;padding:10px;background:#080808;border:1px solid #67321b;border-radius:13px;box-shadow:none}.dap-filter-menu>label,.dap-filter-menu>button{display:flex;align-items:center;gap:10px;padding:8px;border:0;background:none;color:#bbb;width:100%;font:11px 'Roboto Mono',monospace;text-align:left;border-radius:6px;cursor:pointer}.dap-filter-menu>label:hover,.dap-filter-menu>button:hover{background:#ff662610;color:var(--orange)}.dap-filter-menu input{accent-color:var(--orange)}.dap-notice{font:9px/1.5 'Roboto Mono',monospace;color:#6d6d6d;min-height:17px;flex-shrink:0;margin-bottom:9px}.dap-notice.is-error{color:var(--orange)}
|
||||
.dap-gallery-viewport{flex:1;min-height:0;overflow-y:scroll;overflow-x:hidden;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:#393939 #000;padding-right:3px}.dap-gallery{column-width:var(--card-min,420px);column-gap:14px;padding-bottom:20px;min-height:101%;overflow:visible}.dap-card{position:relative;break-inside:avoid;min-width:0;width:100%;overflow:hidden;border:1px solid #23170f;border-radius:16px;background:#030303;margin:0 0 14px;transition:border-color .15s,box-shadow .15s}.dap-card:hover{border-color:#6b351f;box-shadow:none}.dap-card-media{position:relative;min-height:100px;cursor:zoom-in;overflow:hidden;background:#030303;line-height:0}.dap-card-media>video{display:block;width:100%;height:auto;min-height:130px}.dap-card-media>.dap-icon{position:absolute;inset:0;margin:auto;width:30px;height:30px;color:#fff7;filter:drop-shadow(0 1px 4px #000)}.dap-compare-host>.dap-generated{display:block;width:100%;height:auto;min-height:120px;user-select:none}.dap-original-cover{position:absolute;inset:0;opacity:0;pointer-events:none}.dap-original-cover>img{display:block;width:100%;height:100%;object-fit:contain;user-select:none}.dap-compare-line{position:absolute;top:0;bottom:0;width:1px;background:white;mix-blend-mode:difference;opacity:0;pointer-events:none}.dap-compare-host.comparing>.dap-original-cover,.dap-compare-host.comparing>.dap-compare-line{opacity:1}.dap-card-tools{position:absolute;top:8px;right:8px;display:flex;gap:5px;opacity:0;transform:translateY(-3px);transition:opacity .15s,transform .15s}.dap-card:hover>.dap-card-tools,.dap-card:focus-within>.dap-card-tools,.dap-card-tools:has(.selected){opacity:1;transform:translateY(0)}.dap-card-tools .dap-icon-button{background:#000b;border:1px solid #59321e;border-radius:20px;padding:5px;color:#cf7a51}.dap-card-tools .dap-icon{width:14px;height:14px}.dap-card-tools .selected{background:var(--orange);color:#000}.dap-card-tools .dap-icon-button:hover{background:#180a03;color:#ff8950}.dap-card-footer{display:flex;justify-content:space-between;gap:8px;padding:8px 11px;font-size:11px;color:#898989;line-height:1.3}.dap-card-footer>span:first-child{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.dap-elapsed{font:9px 'Roboto Mono',monospace;color:#686868;white-space:nowrap}.dap-card-tags{font:8px 'Roboto Mono',monospace;color:#74513d;padding:0 11px 8px}.dap-study{position:absolute;left:10px;top:10px;font:8px 'Roboto Mono',monospace;color:#fffb;text-shadow:0 1px 3px #000;pointer-events:none}.dap-card.pending{aspect-ratio:1.65;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px}.dap-card.pending>.dap-card-footer{position:absolute;bottom:0;left:0;right:0}.dap-job-state{font:10px 'Roboto Mono',monospace;color:#8c5a41}.dap-card.stopped .dap-card-error{font:10px/1.5 'Roboto Mono',monospace;color:var(--orange);padding:0 11px 9px;margin:0;max-height:90px;overflow:auto}.dap-empty{column-span:all;min-height:65vh;border-top:1px solid #381b0e;padding:50px 10px;color:#777}.dap-empty>span{font:10px 'Roboto Mono',monospace;color:#bd5e2e}.dap-empty h2{font-size:27px;font-weight:normal;color:#aaa;margin-top:24px}.dap-empty p{font:11px/1.6 'Roboto Mono',monospace;max-width:600px}
|
||||
.dap-modal{border:1px solid #63301a;border-radius:17px;width:min(1400px,94vw);max-width:96vw;max-height:94dvh;padding:18px;overflow:auto}.dap-modal>header{display:flex;align-items:center;justify-content:space-between;gap:15px;font:11px 'Roboto Mono',monospace;color:#dd743f;margin-bottom:15px}.dap-modal>header>span{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.dap-modal>header .dap-icon{width:16px;height:16px}.dap-outline,.dap-primary{border:1px solid #63351e;border-radius:20px;background:#000;color:#d67544;padding:7px 14px;font:10px 'Roboto Mono',monospace!important;cursor:pointer}.dap-primary{background:var(--orange);border-color:var(--orange);color:#000!important}.dap-primary:hover{background:#ff854b}.dap-viewer-modal{width:96vw;max-width:96vw;height:94dvh;max-height:94dvh;overflow:hidden;display:flex;flex-direction:column;padding:15px}.dap-viewer-modal>header{margin-bottom:7px;flex-shrink:0}.dap-viewer-tools{display:flex;align-items:center;justify-content:center;gap:10px;flex-wrap:wrap;flex-shrink:0;margin-bottom:10px}.dap-viewer-tools>button{display:flex;align-items:center;justify-content:center;gap:7px;border:1px solid #282828;border-radius:20px;background:#030303;color:#aaa;padding:6px 11px;min-height:30px;font:10px 'Roboto Mono',monospace}.dap-viewer-tools .dap-icon{width:16px;height:16px}.dap-zoom-value{display:flex;align-items:center;gap:2px;font:10px 'Roboto Mono',monospace;color:#aaa}.dap-zoom-value input{width:45px;appearance:textfield;-moz-appearance:textfield;padding:5px 1px;background:transparent;border:0;text-align:right;font:10px 'Roboto Mono',monospace}.dap-zoom-value input::-webkit-inner-spin-button{display:none}.dap-viewer-stage{position:relative;flex:1;min-height:0;background:#010101;overflow:hidden;touch-action:none;outline:none;cursor:zoom-in}.dap-viewer-stage.zoomed{cursor:grab}.dap-viewer-stage:active{cursor:grabbing}.dap-viewer-surface{position:absolute;left:0;top:0;transform-origin:0 0;line-height:0;will-change:transform;user-select:none}.dap-viewer-surface>.dap-generated{width:100%;height:100%;min-height:0}.dap-viewer-surface>.dap-original-cover img{object-fit:contain}.dap-viewer-hint{font:9px 'Roboto Mono',monospace;color:#666;text-align:center;margin:10px 0 0;flex-shrink:0}.dap-viewer-video{width:100%;height:100%;object-fit:contain;display:block}
|
||||
.dap-reference-modal{width:96vw}.dap-reference-layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:25px}.dap-reference-left{min-width:0}.dap-reference-tools{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:14px}.dap-editor-tool{padding:7px 12px;border:1px solid #333;border-radius:20px;background:#000;color:#aaa;font:10px 'Roboto Mono',monospace!important}.dap-editor-tool.active{border-color:var(--orange);color:var(--orange)}.dap-reference-tools>input[type=range]{width:90px;accent-color:var(--orange)}.dap-mask-stage{position:relative;max-width:100%;margin:0 auto;line-height:0;background:#131313}.dap-mask-stage canvas{display:block;width:100%;height:auto}.dap-mask-stage canvas+canvas{position:absolute;inset:0;touch-action:none;cursor:crosshair}.dap-reference-options{max-height:69vh;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;scrollbar-color:#393939 #000;padding-right:4px}.dap-reference-options .dap-field{min-height:28px}.dap-reference-options .dap-field-hint{line-height:1.6}.dap-reference-preview{width:100%;height:auto;display:block;margin-top:12px;border:1px solid #3e281a;border-radius:8px}.dap-reference-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:18px}.dap-editor-status{font:10px/1.5 'Roboto Mono',monospace;color:#b06c46;margin:12px 0}.dap-folder-list{display:flex;flex-direction:column;gap:8px}.dap-folder-list>.dap-icon-button{justify-content:flex-start;border:1px solid #222;border-radius:8px;padding:10px}.dap-folder-path{font:11px 'Roboto Mono',monospace;color:#888;overflow-wrap:anywhere;padding:10px 0 20px}
|
||||
@keyframes dap-spin{to{transform:rotate(360deg)}}
|
||||
@media(min-width:2200px){.dap-header{height:160px}.dap-layout{height:calc(100dvh - 160px)}}
|
||||
@media(max-width:1250px){.dap-header{height:105px}.dap-layout{height:calc(100dvh - 105px);grid-template-columns:320px minmax(0,1fr)}.dap-views{gap:10px}.dap-views input[type=range]{width:100px}.dap-main{padding-left:12px}.dap-credit{font-size:9px!important}.dap-filters{justify-content:flex-start}.dap-filter>span{display:none}.dap-model summary>small{max-width:105px}}
|
||||
@media(max-width:760px){.dap-header{height:85px;padding:14px 12px 0;gap:8px}.dap-brand{display:block}.dap-brand img{width:115px;height:24px}.dap-brand>span{display:block;transform:none;font-size:11px;margin-top:6px}.dap-actions{gap:5px}.dap-actions>.dap-icon-button{display:none}.dap-credit{font-size:8px!important;max-width:95px;text-align:right}.dap-run{min-width:95px;padding:4px 10px;gap:6px}.dap-layout{height:calc(100dvh - 85px);display:flex;flex-direction:column;overflow-y:auto;padding:0 12px}.dap-side{height:auto;max-height:65vh;overflow-y:auto;flex-shrink:0;border-right:0;border-bottom:1px solid #2b1b12;padding-right:4px}.dap-controls{padding-left:0}.dap-main{height:75vh;min-height:400px;padding:15px 0 0;flex-shrink:0}.dap-refs{grid-template-columns:repeat(2,minmax(0,1fr))}.dap-views input[type=range]{width:80px}.dap-toolbar{gap:8px}.dap-project{font-size:11px}.dap-filters{gap:6px}.dap-filter select{max-width:120px;font-size:8px}.dap-filter-models>summary>span{max-width:140px}.dap-reference-layout{grid-template-columns:1fr}.dap-reference-options{max-height:none}.dap-reference-modal{max-height:95dvh}.dap-viewer-modal{height:95dvh}.dap-viewer-tools{gap:5px}.dap-viewer-tools>button{font-size:9px;padding:5px 7px}.dap-viewer-hint{font-size:8px;line-height:1.5}.dap-empty h2{font-size:21px}}
|
||||
@media(prefers-reduced-motion:reduce){.dap *,.dap-modal *{animation:none!important;transition:none!important}}
|
||||
|
||||
.dap-date-row input[type=date]{margin-left:auto;min-width:0;width:105px;border:0;background:transparent;color:#9a623f;font:9px 'Roboto Mono',monospace;cursor:pointer}.dap-date-row input[type=date]:hover{color:var(--orange)}.dap-operation-note{flex-shrink:0;font:10px/1.4 'Roboto Mono',monospace;color:var(--orange);margin:8px 0 0;text-align:center}
|
||||
|
||||
.dap-field-step{width:10px;min-width:10px;height:16px;flex:none;border:0;padding:0;color:#999}.dap-field-step .dap-icon{width:9px;height:13px;stroke-width:1.4}.dap-field-step.next{transform:rotate(180deg)}.dap-field select{padding-right:0}
|
||||
|
||||
/* 1.0.56: immediate shell, in-panel folders and live progress */
|
||||
.dap-stop{border:1px solid #ef382e;background:#cf2922;color:white!important;border-radius:25px;padding:8px 22px;font-weight:bold!important;min-width:100px;cursor:pointer}.dap-stop:hover{background:#f34135;box-shadow:none}.dap-stop:disabled{opacity:.24;cursor:default}.dap-project{background:none;border:0;text-align:left;cursor:pointer;max-width:55%}.dap-project:hover{color:var(--orange)}
|
||||
.dap-work>summary{display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:8px 0;border-bottom:1px solid #292018}.dap-work>summary:hover{color:var(--orange)}.dap-work>summary .dap-icon{width:12px;height:12px}.dap-work[open]>summary .dap-icon{transform:rotate(180deg)}.dap-work>div{padding-top:10px}.dap-video-choice{margin:0 0 25px}.dap-video-choice>button{background:#000;border:1px solid #333;border-radius:22px;color:#aaa;padding:9px 16px;margin-right:8px;font:11px 'Roboto Mono',monospace}.dap-video-choice>button.active{border-color:var(--orange);color:var(--orange)}
|
||||
.dap-views>button:first-child .dap-icon{width:40px;height:24px}.dap-card-tools .dap-icon-button:first-child .dap-icon{width:23px}
|
||||
.dap-folder-modal{width:min(1000px,90vw);height:75vh;display:flex;flex-direction:column}.dap-folder-navigation,.dap-folder-footer{display:flex;gap:10px;flex-shrink:0;margin:10px 0}.dap-folder-navigation input{flex:1;min-width:0}.dap-folder-navigation input,.dap-folder-footer input{background:#111;color:#ccc;border:1px solid #444;border-radius:8px;padding:9px;font:12px 'Roboto Mono',monospace}.dap-folder-list{flex:1;overflow:auto;min-height:0}.dap-folder-file{padding:10px 14px;color:#999;font:12px 'Roboto Mono',monospace;border:1px solid transparent;border-radius:6px}.dap-folder-file.selected{background:#ff662622;border-color:var(--orange);color:#eee}.dap-folder-footer{flex-wrap:wrap}
|
||||
.dap-progress-track{height:3px;background:#271308;overflow:hidden;border-radius:2px}.dap-progress-track>i{display:block;height:100%;width:0;background:#ff6626;box-shadow:none;transition:width .7s linear}.dap-total-progress{margin:0 0 12px;flex-shrink:0}.dap-total-progress>span{display:block;text-align:right;font:10px 'Roboto Mono',monospace;color:#b47753;margin-top:8px}.dap-card-progress{position:absolute;bottom:0;left:0;right:0}.dap-progress-track.indeterminate>i{width:28%!important;animation:dap-progress 1.8s ease-in-out infinite}
|
||||
@keyframes dap-light{0%{opacity:1}70%,100%{opacity:0}}@keyframes dap-progress{from{transform:translateX(-110%)}to{transform:translateX(470%)}}
|
||||
.dap-generated{opacity:1;transition:opacity .2s}.dap-reference-preview[hidden],.dap-total-progress[hidden]{display:none}.dap-field select{min-width:35%;cursor:pointer}
|
||||
|
||||
/* V4: DOGMA artwork, quiet surfaces and consistent interaction. */
|
||||
.dap,.dap-modal{--muted:#777;--line:#303030;scrollbar-width:thin;scrollbar-color:#393939 transparent}
|
||||
.dap *,.dap-modal *{scrollbar-width:thin;scrollbar-color:#393939 transparent}
|
||||
.dap *::-webkit-scrollbar,.dap-modal *::-webkit-scrollbar{width:4px;height:4px}
|
||||
.dap *::-webkit-scrollbar-thumb,.dap-modal *::-webkit-scrollbar-thumb{background:#393939;border-radius:4px}
|
||||
.dap *::-webkit-scrollbar-track,.dap-modal *::-webkit-scrollbar-track{background:transparent}
|
||||
.dap button,.dap-modal button{box-shadow:none!important}
|
||||
.dap-run-group{display:flex;align-items:center;border:1px solid #303030;border-radius:30px;height:34px}
|
||||
.dap-run-counter{display:flex;align-items:center;gap:5px;padding:0 13px 0 14px;height:100%}
|
||||
.dap-run-counter input{appearance:textfield;background:none;border:0;color:#888;width:24px;text-align:center;padding:0;font:15px Arial,sans-serif}
|
||||
.dap-run-counter input::-webkit-inner-spin-button{display:none}
|
||||
.dap-run-counter>div{display:flex;flex-direction:column;gap:0}
|
||||
.dap-run-counter button{padding:0;width:14px;height:12px;border:0;color:#666}
|
||||
.dap-run-counter button:hover{color:#ddd}
|
||||
.dap-run-counter .dap-icon{width:14px;height:12px;stroke-width:2}
|
||||
.dap-run-up{transform:rotate(180deg)}
|
||||
.dap-run{height:34px;min-width:165px;margin:-1px;position:relative;font-size:14px!important;padding:4px 14px}
|
||||
.dap-credit{font-size:10px!important;color:#535353}
|
||||
.dap-refs{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.dap button.dap-add{background:#000;color:#777}
|
||||
.dap button.dap-add:hover:not(:disabled){background:#000;border-color:#272727;color:#777}
|
||||
.dap-add>.dap-add-hover{display:none;width:24px;height:24px;stroke-width:.6}
|
||||
.dap-add:hover>.dap-icon:first-child{display:none}
|
||||
.dap-add:hover>.dap-add-hover{display:block}
|
||||
.dap-field{border:0;background:transparent;min-height:30px;margin-bottom:5px;padding:4px 10px;border-radius:18px}
|
||||
.dap-field:hover,.dap-field:focus-within{background:#191919}
|
||||
.dap-field>span{pointer-events:none;position:relative;z-index:1}
|
||||
.dap-field input:not([type=checkbox]):not([type=color]){background:transparent}
|
||||
.dap-field.has-select>select{position:absolute;inset:0;width:100%;height:100%;max-width:none;padding:0 30px 0 40%;text-align:right;cursor:pointer;border-radius:18px}
|
||||
.dap-field-step{position:relative;z-index:2;width:12px;min-width:12px;flex:0 0 12px}
|
||||
.dap-field-step .dap-icon{width:10px;height:13px}
|
||||
.dap-field-step.next{margin-left:auto}
|
||||
.dap-field.has-select>span{flex:0 0 38%;overflow:hidden}
|
||||
.dap-work{margin-top:-5px}
|
||||
.dap-work-label{border-top:1px solid #333;padding-top:12px}
|
||||
.dap-work>summary{border:0;padding:12px 8px 12px 0;border-radius:0;gap:14px}
|
||||
.dap-work>summary .dap-icon{color:var(--orange);flex-shrink:0}
|
||||
.dap-filename-preview{font:11px/1.6 'Roboto Mono',monospace;color:#bababa;padding:0;overflow-wrap:anywhere;white-space:normal}
|
||||
.dap-work>summary:hover{background:#111}
|
||||
.dap-workspace-row{display:flex;align-items:center;gap:4px}
|
||||
.dap-workspace-row>.dap-icon-button{flex:none;color:#777}
|
||||
.dap-workspace-row>.dap-workspace-button{flex:1;width:auto;min-width:0}
|
||||
.dap-workspace-button{border:0;border-radius:16px;padding:8px 0;min-width:0;flex:1}
|
||||
.dap-workspace-button span{font:11px Arial,sans-serif}
|
||||
.dap-workspace-button:hover{background:#171717}
|
||||
.dap-model{margin:14px 0 0}
|
||||
.dap-model-head{gap:10px}
|
||||
.dap-model summary{border:0;border-top:1px solid #333;border-radius:0;min-height:32px;padding:7px 5px 5px 0;gap:10px;font-size:14px}
|
||||
.dap-model summary:hover{background:#131313}
|
||||
.dap-model summary>small{font-size:8px}
|
||||
.dap-model-body{padding-top:12px}
|
||||
.dap-advanced summary{border:0}
|
||||
.dap-field-hint{font-size:8px;color:#4d4d4d}
|
||||
.dap-project{color:#aaa;max-width:70%}
|
||||
.dap-views>button:first-child .dap-icon{width:21px;height:21px}
|
||||
.dap-filters,.dap-filter,.dap-filter-models>summary,.dap-filter-menu>label,.dap-filter-menu>button,.dap-filter select{font-family:Arial,Helvetica,sans-serif!important;font-size:11px}
|
||||
.dap-filter{padding:0;display:inline-flex;min-width:100px;max-width:260px;overflow:visible}
|
||||
.dap-filter>span{position:absolute;left:10px;z-index:1;pointer-events:none;font:10px Arial,sans-serif;display:block!important;color:#686868}
|
||||
.dap-filter select{width:100%;min-width:0;max-width:260px;padding:6px 22px 6px 70px;border-radius:20px;min-height:28px}
|
||||
.dap-filter>.dap-icon{pointer-events:none}
|
||||
.dap-filter-models>summary{min-height:29px}
|
||||
.dap-error-filter{background:transparent;border:1px solid #303030;color:#888;border-radius:20px;padding:6px 11px;font:11px Arial,sans-serif}
|
||||
.dap-error-filter[aria-pressed=true]{color:#bbb}
|
||||
.dap-total-progress{position:absolute;inset:0 0 auto;margin:0;z-index:3;height:7px}
|
||||
.dap-total-progress .dap-progress-track{height:7px;border-radius:0;background:#272727}
|
||||
.dap-total-progress>span{position:absolute;top:9px;right:22px;color:#777;font:9px 'Roboto Mono',monospace;pointer-events:none;margin:0}
|
||||
.dap-header{padding-top:31px}
|
||||
.dap-progress-track>i{box-shadow:none}
|
||||
.dap-card-progress{top:0;bottom:auto;height:5px;border-radius:0;background:#34251d}
|
||||
.dap-gallery{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--card-min,420px)),1fr));gap:14px;align-items:start;align-content:start;column-width:auto;min-height:0}
|
||||
.dap-card{margin:0;background:#181818;border-color:transparent;box-shadow:none;border-radius:18px}
|
||||
.dap-card:hover{box-shadow:none;border-color:#454545}
|
||||
.dap-card.pending{aspect-ratio:1.8;display:flex;min-height:215px}
|
||||
.dap-loading-logo{position:absolute;left:50%;top:47%;transform:translate(-50%,-50%);width:20%;max-width:160px;min-width:65px;mix-blend-mode:screen;pointer-events:none}
|
||||
.dap-card.stopped .dap-loading-logo{display:none}
|
||||
.dap-card-footer{display:flex;align-items:center;gap:18px;min-height:36px;padding:10px 12px;color:#686868;background:#181818;font:11px/1.4 Arial,Helvetica,sans-serif}
|
||||
.dap-result-name{flex:0 1 auto;min-width:0;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}
|
||||
.dap-elapsed{margin-left:auto;font:10px Arial,Helvetica,sans-serif;color:#696969}
|
||||
.dap-card-tags{padding:0;color:#626262;white-space:nowrap;font:10px Arial,Helvetica,sans-serif}
|
||||
.dap-job-state{color:#797979;font:10px Arial,Helvetica,sans-serif;white-space:nowrap}
|
||||
.dap-error-content{display:none;padding:25px 20px 50px;max-height:100%;width:100%;overflow:auto;color:#ccc;line-height:1.6;font:11px/1.7 'Roboto Mono',monospace}
|
||||
.dap-error-content>span{display:block;color:#777;margin:0 0 18px;font:11px Arial,sans-serif}
|
||||
.dap-error-content p{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.dap-card.failed .dap-error-content{display:block}
|
||||
.dap-error-countdown{position:absolute;right:12px;top:14px;color:#ccc;background:#181818;font:10px 'Roboto Mono',monospace}
|
||||
.dap-error-countdown:empty{display:none}
|
||||
.dap-card-media{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='3' fill='white' stroke='black' stroke-width='1'/%3E%3C/svg%3E") 8 8,crosshair}
|
||||
.dap-card-media video{object-fit:contain}
|
||||
.dap-card-media>.dap-icon{color:var(--orange);width:38px;height:38px;filter:none}
|
||||
.dap-card-media>.dap-icon path{fill:none;stroke:currentColor;stroke-width:1.4}
|
||||
.dap-card-media.playing>.dap-icon,.dap-card-media:hover>.dap-icon{opacity:0}
|
||||
.dap-video-duration{position:absolute;bottom:10px;right:10px;font:11px 'Roboto Mono',monospace;color:#eee;line-height:1.4;background:#0009;padding:2px 5px;border-radius:3px}
|
||||
.dap-card-tools .dap-ab{font:15px Arial,sans-serif;min-width:38px;color:#ccc;border-color:#555}
|
||||
.dap-card-tools .selected{background:var(--orange);color:#000;border-color:var(--orange)}
|
||||
.dap-card-tools .dap-icon-button:hover{color:var(--orange);background:#181818}
|
||||
.dap-empty{grid-column:1/-1}
|
||||
.dap-reference-modal{height:94dvh;max-height:94dvh;display:flex;flex-direction:column}
|
||||
.dap-reference-layout{flex:1;min-height:0;grid-template-columns:minmax(0,1fr) 300px}
|
||||
.dap-reference-left{display:flex;flex-direction:column;min-height:0}
|
||||
.dap-reference-tools{flex-shrink:0}
|
||||
.dap-mask-viewport{position:relative;overflow:hidden;flex:1;min-height:200px;touch-action:none;outline:0;background:#070707}
|
||||
.dap-mask-stage{position:absolute;left:0;top:0;margin:0;max-width:none;transform-origin:0 0}
|
||||
.dap-mask-stage canvas{width:100%;height:100%}
|
||||
.dap-mask-viewport.pan,.dap-mask-viewport.pan canvas{cursor:grab!important}
|
||||
.dap-reference-options{height:100%;max-height:none}
|
||||
.dap-editor-status{flex-shrink:0;min-height:15px;font-size:9px;color:#888}
|
||||
.dap-reference-footer{flex-shrink:0}
|
||||
.dap-reference-preview{cursor:pointer;border-color:#333;border-radius:5px}
|
||||
.dap-reference-preview:hover{border-color:var(--orange)}
|
||||
.dap-preview-tools{display:flex;gap:8px;margin-top:8px}
|
||||
.dap-preview-tools button{font:10px Arial,sans-serif!important;padding:7px 10px}
|
||||
.dap-video-compare{display:grid;grid-template-columns:1fr 1fr;gap:10px;cursor:default}
|
||||
.dap-video-panel{position:relative;min-width:0;min-height:0;display:flex;align-items:center}
|
||||
.dap-video-panel>video,.dap-video-panel>img{width:100%;height:100%;object-fit:contain}
|
||||
.dap-video-panel>span{position:absolute;top:10px;left:12px;font:18px Arial,sans-serif;color:var(--orange)}
|
||||
.dap-video-sync{display:flex;align-items:center;gap:14px;padding:12px;flex-shrink:0}
|
||||
.dap-video-sync>input{flex:1;accent-color:var(--orange)}
|
||||
.dap-video-sync>button{background:#181818;border:1px solid #333;border-radius:15px;padding:6px 15px}
|
||||
.dap-prompt-modal{width:min(900px,90vw)}
|
||||
.dap-prompt-modal textarea{width:100%;height:45vh;resize:vertical;background:#111;border:1px solid #333;padding:15px;line-height:1.6;margin-bottom:12px}
|
||||
@media(max-width:760px){.dap-run{min-width:90px}.dap-run-counter{padding:0 8px;gap:2px}.dap-card-footer{gap:8px}.dap-reference-layout{grid-template-columns:1fr;overflow:auto;display:flex;flex-direction:column}.dap-reference-left{height:55vh;flex-shrink:0}.dap-reference-options{height:auto;overflow:visible}.dap-total-progress>span{display:none}.dap-header{padding-top:24px}.dap-video-compare{grid-template-columns:1fr;grid-template-rows:1fr 1fr}}
|
||||
|
||||
.dap-refs:has(>.dap-ref:first-child:nth-last-child(2)){grid-template-columns:1.75fr 1fr}
|
||||
.dap-refs:has(>.dap-ref:first-child:nth-last-child(2))>.dap-add{aspect-ratio:auto}
|
||||
.dap-workspace-explorer{display:inline-flex;align-items:center;justify-content:center;gap:5px;flex:none;background:transparent;border:0;border-radius:10px;padding:8px 6px;color:#999;font:10px Arial,sans-serif;white-space:nowrap}
|
||||
.dap-workspace-explorer .dap-icon{width:13px;height:13px}
|
||||
.dap-workspace-explorer:hover,.dap-workspace-explorer:focus-visible{color:var(--orange);background:#171717}
|
||||
|
||||
|
||||
|
||||
|
||||
/* Shared compact lever: the same 28 × 14 track for every on/off setting. */
|
||||
.dap-toggle{position:relative;display:inline-flex;align-items:center;justify-content:center;flex:0 0 38px;width:38px;min-width:38px;height:32px;padding:0;border:0;border-radius:6px;background:transparent;vertical-align:middle;cursor:pointer}
|
||||
.dap-toggle>input[type=checkbox]{position:absolute;inset:0;z-index:1;width:100%;min-width:100%;max-width:none;height:100%;margin:0;padding:0;opacity:0;cursor:pointer}
|
||||
.dap-toggle-track{display:block;position:relative;flex:none;box-sizing:border-box;width:28px;height:14px;border:1px solid #565656;border-radius:20px;background:#000;pointer-events:none}
|
||||
.dap-toggle-knob{display:block;position:absolute;left:2px;top:2px;width:8px;height:8px;border:0;border-radius:50%;background:#8a8a8a;transition:left .12s ease,background-color .12s;pointer-events:none}
|
||||
.dap-toggle>input:checked+.dap-toggle-track{border-color:var(--orange)}
|
||||
.dap-toggle>input:checked+.dap-toggle-track>.dap-toggle-knob{left:16px;background:var(--orange)}
|
||||
.dap-toggle:hover{background:#181818}
|
||||
.dap-toggle>input:focus-visible+.dap-toggle-track{outline:1px solid var(--orange);outline-offset:4px}
|
||||
.dap-toggle>input:disabled+.dap-toggle-track{opacity:.35}
|
||||
.dap-toggle:has(>input:disabled),.dap-toggle>input:disabled{cursor:default}
|
||||
.dap-ref-tools .dap-toggle{margin-right:auto}
|
||||
.dap-field.has-toggle{padding-top:0;padding-bottom:0}
|
||||
.dap-field.has-toggle>.dap-toggle{flex:0 0 38px;width:38px;margin-right:-5px;overflow:visible;pointer-events:auto;z-index:auto}
|
||||
.dap-model-head{border-top:1px solid #333;gap:7px;align-items:flex-start}
|
||||
.dap-model-head>.dap-toggle{height:34px}
|
||||
.dap-model summary{border-top:0;min-height:34px;padding:0 5px 0 0}
|
||||
.dap-model .dap-advanced>summary{min-height:27px;padding:7px;font:9px/1.5 'Roboto Mono',monospace}
|
||||
.dap-error-filter{display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 0;border:0;border-radius:6px;color:#999;cursor:pointer;white-space:nowrap}
|
||||
.dap-error-filter:hover{background:#181818;color:#ccc}
|
||||
@media(pointer:coarse){.dap-toggle,.dap-model-head>.dap-toggle,.dap-field.has-toggle>.dap-toggle{height:44px;min-width:44px;width:44px;flex-basis:44px}.dap-model summary{min-height:44px}.dap-advanced summary{min-height:30px}}
|
||||
@media(prefers-reduced-motion:reduce){.dap-toggle-knob{transition:none}}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { app } from '../../scripts/app.js';
|
||||
import { api } from '../../scripts/api.js';
|
||||
import { PlatformUI } from './dogma_api_ui.js?v=1.0.56';
|
||||
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.56';
|
||||
const ROOT=new URL('.',import.meta.url);
|
||||
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.56',ROOT);document.head.append(css);
|
||||
let opened=null,queueLock=false;
|
||||
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.56',ROOT)).then(r=>r.json()).catch(()=>({}));
|
||||
|
||||
class ComfyBridge {
|
||||
constructor(node){this.node=node;this.preview=false;this.pricingNodes=new Map();}
|
||||
get widget(){return this.node.widgets.find(w=>w.name==='config');}
|
||||
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V4.json.');return migrateState(s);}
|
||||
async initialize(state){
|
||||
const [defaults,catalog,cached]=await Promise.all([(await fetch(new URL('dogma_api_defaults.json?v=1.0.56',ROOT))).json(),this.request('/catalog'),cachedSchemas]);
|
||||
for(const [key,value] of Object.entries(defaults.models))state.models[key] ||= copy(value);
|
||||
this.catalog=catalog;this.defs=cached;
|
||||
const live=await Promise.allSettled(Object.keys(cached).map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));if(!r.ok)throw new Error(type);const d=await r.json();return [type,d[type]];}));
|
||||
for(const r of live)if(r.status==='fulfilled'&&r.value[1])this.defs[r.value[0]]=r.value[1];
|
||||
if(state.workspace){try{await this.workspace(state.workspace);}catch(e){this.workspaceError=e.message;}}
|
||||
try{
|
||||
const script=[...document.querySelectorAll('script[type=module][src]')].find(x=>x.src.includes('/assets/'));
|
||||
const base=script?.src||new URL('/assets/index.js',location.href).href;
|
||||
const names=this.catalog.frontend;
|
||||
if(names.billing&&names.credits){
|
||||
const [billing,credits]=await Promise.all([import(new URL(names.billing.file,base).href),import(new URL(names.credits.file,base).href)]);
|
||||
this.billing=billing[names.billing.context]();this.nativePricing=billing[names.billing.pricing]();this.formatCredits=credits[names.credits.format];
|
||||
}
|
||||
}catch(e){console.warn('DOGMA: servizi crediti/prezzi non disponibili in questo frontend.');}
|
||||
}
|
||||
save(s){this.widget.value=JSON.stringify(s);this.node.setDirtyCanvas?.(true,true);clearTimeout(this.saveTimer);this.saveTimer=setTimeout(()=>{if(this.node.graph===app.graph)app.graph.change?.();},250);}
|
||||
loadingLogo(){return new URL('./dogma_api_assets/dogma-loading.mp4',ROOT).href;}
|
||||
explorer(path){return this.request('/explorer',{path});}
|
||||
logo(){return new URL('dogma_api_logo.png',ROOT).href;}
|
||||
view(file){if(file?.workspace&&file?.relative)return api.apiURL('/dogma/api/v2/workspace-media?'+new URLSearchParams({workspace:file.workspace,relative:file.relative}));if(file?.url)return file.url;return api.apiURL('/view?'+new URLSearchParams(viewParameters(file)));}
|
||||
async request(path,body){const headers={};if(this.catalog?.access?.token)headers['X-Dogma-Access']=this.catalog.access.token;if(body!==undefined)headers['Content-Type']='application/json';const response=await api.fetchApi('/dogma/api/v2'+path,{method:body===undefined?'GET':'POST',headers,...(body!==undefined?{body:JSON.stringify(body)}:{})});if(!response.ok)throw new Error((await response.text()).slice(0,800));return response.json();}
|
||||
async upload(file){const body=new FormData();body.append('image',file,file.name);body.append('type','input');body.append('subfolder','DOGMA_API');body.append('overwrite','false');const r=await api.fetchApi('/upload/image',{method:'POST',body});if(!r.ok)throw new Error('Caricamento non riuscito.');const d=await r.json();return {file:[d.subfolder,d.name].filter(Boolean).join('/'),kind:file.type.startsWith('video/')?'video':'image'};}
|
||||
async workspace(path){return this.request('/workspace',{path});}
|
||||
async chooseFolder(){return {browse:true};}
|
||||
async mkdir(path,name){return this.request('/mkdir',{path,name});}
|
||||
async folders(path){return this.request('/folders?'+new URLSearchParams({path:path||''}));}
|
||||
async library(){return (await this.request('/library')).records;}
|
||||
async previewReference(ref,settings){return this.request('/reference-preview',{file:ref.file,settings});}
|
||||
async openOutput(id,index){return this.request('/open-output',{id,index});}
|
||||
async credits(){
|
||||
if(!this.billing||!this.formatCredits)return {text:'CREDITS —',title:'Saldo non disponibile. Apri l’account Comfy.'};
|
||||
try{await this.billing.fetchBalance();const raw=this.billing.balance,b=raw&&'value' in raw?raw.value:raw;const amount=b?.effectiveBalanceMicros??b?.amountMicros;if(!Number.isFinite(amount))return {text:'ACCEDI A COMFY',title:'Accedi all’account da Comfy per vedere i crediti.'};return {text:this.formatCredits({cents:amount,locale:'it-IT',numberOptions:{minimumFractionDigits:0,maximumFractionDigits:2}})+' CREDITS LEFT',title:'Saldo dello stesso account e workspace di Comfy'};}catch{return {text:'CREDITS —',title:'Saldo temporaneamente non disponibile. Clicca per aggiornare.'};}
|
||||
}
|
||||
inputSpec(state,f,key){const m=state.models[f.key],frames=m.engine==='frames';return inputSpec(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters,key);}
|
||||
parameterSpecs(state,f){const m=state.models[f.key],frames=m.engine==='frames';return parameterSpecs(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters);}
|
||||
changeModel(state,f){const m=state.models[f.key],frames=m.engine==='frames',key=frames?'frames':'parameters';m[key]=modelValues(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],m[key]);}
|
||||
price(state,f){
|
||||
if(!this.nativePricing||!this.defs)return '';
|
||||
const m=state.models[f.key],frames=f.key==='seedance'&&m.engine==='frames',type=frames?'ByteDance2FirstLastFrameNode':f.type,def=this.defs[type];if(!def)return '';
|
||||
let n=this.pricingNodes.get(type);if(!n){n={constructor:{nodeData:def},inputs:[],widgets:[],isInputConnected:i=>!!n.inputs[i]?.link};this.pricingNodes.set(type,n);}
|
||||
const refs=activeReferences(state),images=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
|
||||
const values=frames?m.frames:m.parameters;n.widgets=Object.entries(values).map(([name,value])=>({name,value}));
|
||||
n.inputs=[];
|
||||
if(f.key==='nano'&&images.length)n.inputs.push({name:'images',link:1});
|
||||
else if(f.key==='seedance'&&frames){for(const r of images)n.inputs.push({name:r.role==='last'?'last_frame':'first_frame',link:1});}
|
||||
else if(f.key==='seedance'){images.forEach((r,i)=>n.inputs.push({name:`model.reference_images.image_${i+1}`,link:1}));videos.forEach((r,i)=>n.inputs.push({name:`model.reference_videos.video_${i+1}`,link:1}));}
|
||||
else images.forEach((r,i)=>n.inputs.push({name:`${f.key==='flux'?'':'model.'}images.image_${i+1}`,link:1}));
|
||||
try{return this.nativePricing.getNodeDisplayPrice(n,new Map(Object.entries(values)))||'';}catch{return '';}
|
||||
}
|
||||
async check(state,compiled){
|
||||
const types=[...new Set(Object.values(compiled.output).map(n=>n.class_type))];
|
||||
const available=await Promise.all(types.map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));return r.ok&&(await r.json())[type]?type:null;}));
|
||||
const missing=types.filter(t=>!available.includes(t));if(missing.length)throw new Error('Nodi mancanti: '+missing.join(', '));
|
||||
await Promise.all(activeReferences(state).flatMap(ref=>[ref.file,ref.process?.maskFile].filter(Boolean)).map(async file=>{const r=await fetch(this.view(file),{method:'HEAD'});if(!r.ok)throw new Error('Reference assente: '+file+'. Ricaricala dal pannello.');}));
|
||||
}
|
||||
async queue(compiled,batch,state){
|
||||
if(queueLock||app.processingQueue||app.queueItems?.length)throw new Error('Comfy sta già inviando una richiesta. Riprova tra un momento.');
|
||||
queueLock=true;let result=null,used=false;const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
|
||||
const nativeBuild=app.graphToPrompt,nativeQueue=api.queuePrompt;
|
||||
const build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
|
||||
const capture=async function(...args){const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;};
|
||||
app.graphToPrompt=build;api.queuePrompt=capture;
|
||||
try{await app.queuePrompt(0,1);if(!result?.prompt_id)throw new Error('Comfy non ha accettato il batch. Controlla accesso e messaggi di Comfy.');return result.prompt_id;}
|
||||
finally{if(app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(api.queuePrompt===capture)api.queuePrompt=nativeQueue;queueLock=false;}
|
||||
}
|
||||
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state'])api.addEventListener(name,e=>{let d=e.detail;if(name==='execution_start')this.activePrompt=d.prompt_id;if(name==='executing'&&(typeof d==='string'||d===null))d={node:d,prompt_id:this.activePrompt};handler(name,d);},{signal:controller.signal});return ()=>controller.abort();}
|
||||
async history(){const r=await api.fetchApi('/history?max_items=200');if(!r.ok)throw new Error('Cronologia non disponibile.');return r.json();}
|
||||
async cancel(id){const r=await api.fetchApi('/jobs/'+encodeURIComponent(id)+'/cancel',{method:'POST'});if(r.ok)return r.json();if(r.status!==404)throw new Error('Interruzione non riuscita.');await api.fetchApi('/queue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({delete:[id]})});const stopped=await api.fetchApi('/interrupt',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt_id:id})});if(!stopped.ok)throw new Error('Interruzione non riuscita.');}
|
||||
download(state){this.save(state);const url=URL.createObjectURL(new Blob([JSON.stringify(app.graph.serialize(),null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='DOGMA_API_PLATFORM_SESSION.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
|
||||
close(){opened=null;}
|
||||
}
|
||||
app.registerExtension({name:'DOGMA.APIPlatform.2',async beforeRegisterNodeDef(type,data){if(data.name!=='DOGMAAPIPlatformV1')return;const previous=type.prototype.onNodeCreated;type.prototype.onNodeCreated=function(...args){const result=previous?.apply(this,args),config=this.widgets?.find(w=>w.name==='config');if(config){config.type='hidden';config.computeSize=()=>[0,-4];}this.addWidget('button','APRI DOGMA / API PLATFORM',null,()=>{if(opened){opened.root?.focus();return;}try{opened=new PlatformUI(new ComfyBridge(this));opened.open().catch(e=>{opened?.close();opened=null;app.ui.dialog.show(e.message);});}catch(e){opened=null;app.ui.dialog.show(e.message);}},{serialize:false});this.size=[390,110];return result;};}});
|
||||
@@ -0,0 +1,60 @@
|
||||
import {copy} from './dogma_api_core.js?v=1.0.56';
|
||||
import {openViewer,copyFullImage} from './dogma_api_viewer.js?v=1.0.56';
|
||||
|
||||
export async function referenceEditor(ui,ref){
|
||||
const make=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
const button=(text,fn,cls='dap-outline')=>{const b=make('button',text,cls);b.type='button';b.onclick=fn;return b;};
|
||||
const box=ui.modalBox('REFERENCE / CROP / MASK','dap-reference-modal'),layout=make('div','','dap-reference-layout'),left=make('div','','dap-reference-left'),right=make('div','','dap-reference-options');
|
||||
const tools=make('div','','dap-reference-tools'),viewport=make('div','','dap-mask-viewport'),stage=make('div','','dap-mask-stage'),base=make('canvas'),overlay=make('canvas');stage.append(base,overlay);viewport.append(stage);left.append(tools,viewport);
|
||||
const cached=ref.editorDraft||{},draft={enabled:true,mask:false,source:'paint',maskMode:'edit',flip:false,invert:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:false,targetWidth:0,targetHeight:0,segment:0,prompt:'',background:'#ff00ff',...copy(cached.process||ref.process||{})};
|
||||
layout.append(left,right);box.append(layout);const status=make('div','','dap-editor-status');left.append(status);
|
||||
let tool=cached.tool||'brush',brush=cached.brush||12,down=null,maskChanged=!!cached.paint,previewFile=Object.hasOwn(cached,'previewFile')?cached.previewFile:ref.processedPreview||null,scale=1,x=0,y=0,space=false,ready=false,paintData=cached.paint||null,revision=0;
|
||||
const undo=[],fields=new Map(),mask=make('canvas'),mc=mask.getContext('2d',{willReadFrequently:true}),oc=overlay.getContext('2d',{willReadFrequently:true}),bc=base.getContext('2d',{willReadFrequently:true});
|
||||
const persist=()=>{if(!ready)return;ref.editorDraft={process:copy(draft),paint:paintData,previewFile,brush,tool,view:{scale,x,y}};ui.save();};
|
||||
box.addEventListener('close',persist);
|
||||
const image=new Image();image.crossOrigin='anonymous';image.src=ref.preview||ui.bridge.view(ref.file);
|
||||
try{await image.decode();if(!box.isConnected)return;}catch{status.textContent='Reference assente. Sostituiscila per modificarla.';left.append(button('Sostituisci reference',()=>{box.close();ui.pickReferences(ref);}));return;}
|
||||
base.width=overlay.width=mask.width=image.naturalWidth;base.height=overlay.height=mask.height=image.naturalHeight;stage.style.width=mask.width+'px';stage.style.height=mask.height+'px';
|
||||
bc.drawImage(image,0,0);const source=bc.getImageData(0,0,base.width,base.height),initial=mc.createImageData(mask.width,mask.height);
|
||||
for(let i=0;i<source.data.length;i+=4){initial.data[i]=initial.data[i+1]=initial.data[i+2]=255;initial.data[i+3]=255-source.data[i+3];source.data[i+3]=255;}bc.putImageData(source,0,0);mc.putImageData(initial,0,0);
|
||||
const loadMask=async(url,alpha=false,current=()=>true)=>{const saved=new Image();saved.crossOrigin='anonymous';saved.src=url;await saved.decode();const temp=make('canvas');temp.width=mask.width;temp.height=mask.height;const ctx=temp.getContext('2d');ctx.drawImage(saved,0,0,mask.width,mask.height);const pixels=ctx.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){if(!alpha)pixels.data[i+3]=pixels.data[i];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=255;}if(!current())throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');mc.putImageData(pixels,0,0);};
|
||||
try{if(cached.paint)await loadMask(cached.paint,true);else if(draft.maskFile)await loadMask(ui.bridge.view(draft.maskFile));}catch{status.textContent='Maschera salvata non disponibile.';}
|
||||
if(!box.isConnected)return;ready=true;
|
||||
const draw=()=>{
|
||||
oc.clearRect(0,0,mask.width,mask.height);
|
||||
if(draft.mask){const pixels=mc.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){pixels.data[i]=255;pixels.data[i+1]=50;pixels.data[i+2]=160;pixels.data[i+3]=Math.round((draft.invert?255-pixels.data[i+3]:pixels.data[i+3])*.4);}oc.putImageData(pixels,0,0);}
|
||||
if(draft.cropRect&&draft.crop){const [a,b,w,h]=draft.cropRect;oc.strokeStyle='#fff';oc.lineWidth=Math.max(1,2/scale);oc.setLineDash([10/scale,7/scale]);oc.strokeRect(a*mask.width,b*mask.height,w*mask.width,h*mask.height);oc.setLineDash([]);}
|
||||
};
|
||||
const updateView=()=>{stage.style.transform=`translate(${x}px,${y}px) scale(${scale})`;draw();};
|
||||
const fit=()=>{scale=Math.min((viewport.clientWidth-24)/mask.width,(viewport.clientHeight-24)/mask.height);x=(viewport.clientWidth-mask.width*scale)/2;y=(viewport.clientHeight-mask.height*scale)/2;updateView();persist();};
|
||||
const at=(next,cx,cy)=>{next=Math.max(.03,Math.min(16,next));const ratio=next/scale;x=cx-(cx-x)*ratio;y=cy-(cy-y)*ratio;scale=next;updateView();persist();};
|
||||
viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect();at(scale*Math.exp(-e.deltaY*.0017),e.clientX-r.left,e.clientY-r.top);},{passive:false});
|
||||
box.addEventListener('keydown',e=>{if(e.code==='Space'&&!['INPUT','SELECT','TEXTAREA'].includes(e.target.tagName)){e.preventDefault();space=true;viewport.classList.add('pan');}});box.addEventListener('keyup',e=>{if(e.code==='Space'){space=false;viewport.classList.remove('pan');}});
|
||||
const preview=make('img','','dap-reference-preview');preview.alt='Anteprima della reference preparata';preview.hidden=!previewFile;if(previewFile)preview.src=ui.bridge.view(previewFile);
|
||||
const previewTools=make('div','','dap-preview-tools');
|
||||
const mark=()=>{revision++;previewFile=null;preview.hidden=true;previewTools.hidden=true;status.textContent='Modifiche conservate · Anteprima per controllare il risultato.';draw();persist();};
|
||||
const saveUndo=()=>{undo.push({pixels:mc.getImageData(0,0,mask.width,mask.height),rect:draft.cropRect?copy(draft.cropRect):null});if(undo.length>10)undo.shift();};
|
||||
const setTool=value=>{tool=value;for(const b of tools.querySelectorAll('[data-tool]'))b.classList.toggle('active',b.dataset.tool===value);overlay.style.cursor=value==='hand'?'grab':value==='crop'?'cell':'crosshair';persist();};
|
||||
for(const [key,title] of [['brush','Pennello'],['erase','Gomma'],['crop','Crop rettangolare'],['hand','Sposta']]){const b=button(title,()=>setTool(key),'dap-editor-tool');b.dataset.tool=key;tools.append(b);}
|
||||
const size=make('input');size.type='range';size.min='1';size.max='180';size.value=String(brush);size.setAttribute('aria-label','Dimensione pennello');size.oninput=()=>{brush=Number(size.value);persist();};tools.append(size);
|
||||
const changedPaint=()=>{maskChanged=true;paintData=mask.toDataURL('image/png');mark();};
|
||||
tools.append(button('Undo',()=>{const previous=undo.pop();if(!previous)return;mc.putImageData(previous.pixels,0,0);draft.cropRect=previous.rect;changedPaint();}),button('Pulisci',()=>{saveUndo();mc.clearRect(0,0,mask.width,mask.height);delete draft.cropRect;draft.source='paint';fields.get('source').value='paint';changedPaint();}),button('Adatta',fit));
|
||||
const point=e=>{const r=overlay.getBoundingClientRect();return [Math.max(0,Math.min(mask.width,(e.clientX-r.left)/scale)),Math.max(0,Math.min(mask.height,(e.clientY-r.top)/scale))];};
|
||||
const stroke=(from,to)=>{mc.globalCompositeOperation=tool==='erase'?'destination-out':'source-over';mc.lineWidth=brush*mask.width/1000;mc.strokeStyle='#fff';mc.lineCap='round';mc.beginPath();mc.moveTo(...from);mc.lineTo(...to);mc.stroke();mc.globalCompositeOperation='source-over';draft.mask=true;draft.source='paint';fields.get('mask').checked=true;fields.get('source').value='paint';};
|
||||
viewport.onpointerdown=e=>{if(e.button===2)return;e.preventDefault();viewport.focus();viewport.setPointerCapture(e.pointerId);const pan=tool==='hand'||space||e.button===1;if(pan)down={pan:true,x,y,cx:e.clientX,cy:e.clientY};else{saveUndo();down={first:point(e),last:point(e)};if(tool!=='crop')stroke(down.first,[down.first[0]+.01,down.first[1]]);draw();}};viewport.tabIndex=0;
|
||||
viewport.onpointermove=e=>{if(!down)return;if(down.pan){x=down.x+e.clientX-down.cx;y=down.y+e.clientY-down.cy;updateView();return;}const p=point(e);if(tool==='crop'){draft.crop=true;fields.get('crop').checked=true;draft.cropRect=[Math.min(p[0],down.first[0])/mask.width,Math.min(p[1],down.first[1])/mask.height,Math.abs(p[0]-down.first[0])/mask.width,Math.abs(p[1]-down.first[1])/mask.height];}else stroke(down.last,p);down.last=p;draw();};
|
||||
viewport.onpointerup=viewport.onpointercancel=()=>{if(!down)return;const pan=down.pan;down=null;if(pan)persist();else changedPaint();};
|
||||
const field=(name,key,opts={})=>{const input=ui.field(right,name,draft[key],v=>{draft[key]=typeof draft[key]==='number'?Number(v):v;mark();},opts);fields.set(key,input);return input;};
|
||||
right.append(make('div','PREPARAZIONE REFERENCE','dap-label'));
|
||||
field('MASK','mask',{type:'checkbox'});field('MASK MODE','maskMode',{choices:['isolate','edit']});field('MASK SOURCE','source',{choices:['paint','prompt']});field('MASK PROMPT','prompt');field('SEGMENT','segment',{type:'number',min:0,max:128});field('INVERT MASK','invert',{type:'checkbox'});field('HORIZONTAL FLIP','flip',{type:'checkbox'});field('CROP','crop',{type:'checkbox'});
|
||||
field('EXPAND / PX','expand',{type:'number',min:-512,max:512});field('BLUR / PX','blur',{type:'number',min:0,max:128,step:.1});field('FILL HOLES','fillHoles',{type:'checkbox'});field('RESIZE TO MPX','resizeMpx',{type:'checkbox'});field('MEGAPIXELS','megapixels',{type:'number',min:.01,max:64,step:.1});field('CROP WIDTH','targetWidth',{type:'number',min:0,max:16384});field('CROP HEIGHT','targetHeight',{type:'number',min:0,max:16384});field('BACKGROUND','background',{type:'color'});
|
||||
right.append(make('p','Edit colora la maschera. Isolate mantiene l’area selezionata. Prompt calcola SAM3 in anteprima; puoi poi rifinire la maschera con il pennello. Rotella per zoom; Spazio o tasto centrale per spostare.','dap-field-hint'),preview,previewTools);
|
||||
const previewItem=()=>({job:{kind:'image',label:'REFERENCE / ANTEPRIMA',study:true},file:{url:ui.bridge.view(previewFile)},preview:true});
|
||||
const enlarge=()=>{if(previewFile)openViewer(ui,previewItem());};preview.onclick=enlarge;preview.tabIndex=0;preview.setAttribute('role','button');preview.onkeydown=e=>{if(e.key==='Enter')enlarge();};
|
||||
previewTools.append(button('Ingrandisci',enlarge),button('Copia immagine',async()=>{if(!previewFile)return;try{await copyFullImage(ui.bridge.view(previewFile));status.textContent='Immagine copiata alla risoluzione originale.';}catch(e){status.textContent=e.message;}}));previewTools.hidden=!previewFile;
|
||||
async function uploadMask(){const version=revision;if(!maskChanged||draft.source==='prompt')return;const out=make('canvas');out.width=mask.width;out.height=mask.height;const ctx=out.getContext('2d'),pixels=mc.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){const v=pixels.data[i+3];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=v;pixels.data[i+3]=255;}ctx.putImageData(pixels,0,0);const blob=await new Promise(resolve=>out.toBlob(resolve,'image/png'));if(!blob)throw new Error('Maschera non esportata.');const result=await ui.bridge.upload(new File([blob],'DOGMA_mask_'+Date.now()+'.png',{type:'image/png'}));if(version!==revision)throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');draft.maskFile=result.file;maskChanged=false;}
|
||||
async function buildPreview(){const version=revision;await uploadMask();const result=await ui.bridge.previewReference(ref,copy(draft));if(version!==revision)throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');if(result.maskFile){await loadMask(ui.bridge.view(result.maskFile),false,()=>version===revision);Object.assign(draft,{maskFile:result.maskFile,samSource:result.samSource,samPrompt:result.samPrompt,samSegment:result.samSegment});paintData=mask.toDataURL('image/png');maskChanged=false;draw();}previewFile=result.file;preview.src=ui.bridge.view(previewFile);await preview.decode();if(version!==revision){previewFile=null;throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');}preview.hidden=false;previewTools.hidden=false;status.textContent=`${result.width} × ${result.height} · ${result.emptyMask?'SAM3 non ha trovato oggetti: prova un altro prompt.':'Anteprima aggiornata'}`;persist();return result;}
|
||||
const footer=make('div','','dap-reference-footer'),previewButton=button('Anteprima',async()=>{previewButton.disabled=true;status.textContent=draft.source==='prompt'?'SAM3 · Preparazione maschera…':'Preparazione anteprima…';try{await buildPreview();}catch(e){status.textContent='Anteprima non disponibile: '+e.message;}finally{previewButton.disabled=false;}}),apply=button('Applica',async()=>{apply.disabled=true;try{if(!previewFile)await buildPreview();await uploadMask();ref.process=copy(draft);ref.process.enabled=true;ref.processedPreview=previewFile;persist();ui.renderRefs();ui.refreshPrices();box.close();ui.note('Preparazione reference salvata.');}catch(e){status.textContent=e.message;}finally{apply.disabled=false;}},'dap-primary');
|
||||
footer.append(button('Sostituisci file',()=>{box.close();ui.pickReferences(ref);}),previewButton,apply);box.append(footer);setTool(tool);
|
||||
if(cached.view){({scale,x,y}=cached.view);updateView();}else fit();
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,294 @@
|
||||
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask} from './dogma_api_core.js?v=1.0.56';
|
||||
import {icon} from './dogma_api_icons.js?v=1.0.56';
|
||||
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.56';
|
||||
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.56';
|
||||
|
||||
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
export const btn=(text,fn,cls='',aria=text)=>{const b=el('button',text,cls);b.type='button';b.onclick=fn;b.setAttribute('aria-label',aria);b.title=aria;return b;};
|
||||
export const ib=(name,label,fn,cls='')=>{const b=btn('',fn,'dap-icon-button '+cls,label);b.append(icon(name));return b;};
|
||||
const terminal=new Set(['completed','failed','cancelled','missing']);
|
||||
const enumValues={aspect_ratio:['auto','1:1','2:3','3:2','3:4','4:3','4:5','5:4','9:16','16:9','21:9'],resolution:['1K','2K','4K'],'model.background':['auto','opaque','transparent'],'model.quality':['low','medium','high'],'model.size':['auto','1024x1024','1536x1024','1024x1536','2048x2048','2048x1152','1152x2048','3840x2160','2160x3840','Custom'],'model.size_preset':['Custom'],'model.resolution':['480p','720p','1080p','4k'],'model.ratio':['adaptive','16:9','4:3','1:1','3:4','9:16','21:9'],'model.task_type':['reference','edit','extend','auto'],'model.output_format':['mp4'],response_modalities:['IMAGE','IMAGE+TEXT']};
|
||||
const displayName=k=>({'model.task_type':'TASK','model.generate_audio':'AUDIO','model.duration':'DURATION / SEC','model.auto_downscale':'AUTO DOWNSCALE','model.auto_upscale':'AUTO UPSCALE'})[k]||k.replace(/^model\./,'').replaceAll('_',' ').toUpperCase();
|
||||
export class PlatformUI {
|
||||
constructor(bridge){this.bridge=bridge;this.state=bridge.load();this.library=[];this.selection=[];this.cards=new Map();this.urls=new Set();this.closed=false;this.busy=false;}
|
||||
save(){if(!this.closed)this.bridge.save(this.state);}
|
||||
async open(){
|
||||
this.ready=false;
|
||||
this.root=el('dialog','','dap');this.root.setAttribute('aria-label','DOGMA API Platform');
|
||||
this.root.addEventListener('cancel',e=>{e.preventDefault();this.close();});
|
||||
this.root.addEventListener('dragover',e=>{if([...e.dataTransfer.types].includes('Files'))e.preventDefault();});
|
||||
this.root.addEventListener('drop',e=>{e.preventDefault();if(e.dataTransfer.files.length)this.addReferences([...e.dataTransfer.files]);});
|
||||
document.body.append(this.root);this.build();this.root.tabIndex=-1;this.root.showModal();this.root.focus({preventScroll:true});
|
||||
this.unsubscribe=this.bridge.subscribe?.((name,d)=>this.event(name,d));
|
||||
this.note('Apertura · Collegamento a Comfy…');
|
||||
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
|
||||
if(this.closed)return;this.renderControls();this.renderFilters();this.renderGallery();
|
||||
try{await this.bridge.initialize?.(this.state);if(this.closed)return;this.ready=true;this.renderControls();this.updateHeader();this.refreshPrices();this.note(this.bridge.preview?'ANTEPRIMA · Nessuna richiesta API':'Pronto.');}catch(e){this.note('Collegamento non riuscito: '+e.message,true);}
|
||||
Promise.allSettled([this.recover(),this.refreshLibrary(),this.refreshCredits()]);
|
||||
this.timer=setInterval(()=>{this.updateCards();this.refreshPrices();if(this.state.results.some(r=>!terminal.has(r.status)))this.recover();},500);
|
||||
this.creditTimer=setInterval(()=>this.refreshCredits(),30000);
|
||||
}
|
||||
close(){if(this.closed)return;this.save();this.closed=true;clearInterval(this.timer);clearInterval(this.creditTimer);this.unsubscribe?.();for(const modal of [...(this.modals||[])].reverse())modal.close();this.root.close();this.root.remove();for(const u of this.urls)URL.revokeObjectURL(u);this.bridge.close?.();}
|
||||
note(text,bad=false){if(!this.notice)return;this.notice.textContent=text;this.notice.classList.toggle('is-error',bad);}
|
||||
build(){
|
||||
const header=el('header','','dap-header'),brand=el('div','','dap-brand'),logo=el('img');logo.src=this.bridge.logo();logo.alt='DOGMA';brand.append(logo,el('span','API Platform'));
|
||||
const actions=el('div','','dap-actions');this.credit=btn('CREDITS —',()=>this.refreshCredits(),'dap-credit','Aggiorna crediti');
|
||||
this.runButton=btn('',()=>this.run(),'dap-run','Avvia generazioni in parallelo');this.runLabel=el('span','Run');this.runButton.append(this.runLabel,icon('play'));
|
||||
const runGroup=el('div','','dap-run-group'),counter=el('div','','dap-run-counter'),arrows=el('div');this.runCount=el('input');this.runCount.type='number';this.runCount.min='1';this.runCount.max='64';this.runCount.value=String(this.state.runCount||1);this.runCount.setAttribute('aria-label','Ripetizioni Run');
|
||||
const setCount=value=>{const n=Number(value);this.state.runCount=Number.isFinite(n)?Math.max(1,Math.min(64,Math.round(n))):1;this.runCount.value=String(this.state.runCount);this.save();this.updateHeader();};
|
||||
this.runCount.oninput=()=>{if(this.runCount.value!=='')setCount(this.runCount.value);};this.runCount.onchange=()=>setCount(this.runCount.value);arrows.append(ib('chevron','Aumenta ripetizioni',()=>setCount(this.state.runCount+1),'dap-run-up'),ib('chevron','Riduci ripetizioni',()=>setCount(this.state.runCount-1)));counter.append(this.runCount,arrows);runGroup.append(counter,this.runButton);
|
||||
this.stopButton=btn('■ Stop',()=>this.stop(),'dap-stop','Ferma le generazioni DOGMA');this.stopButton.disabled=true;
|
||||
actions.append(this.stopButton,this.credit,ib('download','Salva sessione e workflow',()=>this.bridge.download(this.state)),ib('close','Torna a Comfy',()=>this.close()),runGroup);header.append(brand,actions);
|
||||
const layout=el('div','','dap-layout');this.side=el('aside','','dap-side');const tabs=el('nav','','dap-tabs');
|
||||
this.imageTab=btn('',()=>this.switchMode('image'),'','Image');this.imageTab.append(icon('image'),el('span','Image'));this.videoTab=btn('',()=>this.switchMode('video'),'','Video');this.videoTab.append(icon('video'),el('span','Video'));tabs.append(this.imageTab,this.videoTab);
|
||||
this.editRow=el('div','','dap-edit-mode');this.editRow.append(this.toggle('Image Edit',this.state.imageEdit,v=>{this.state.imageEdit=v;this.save();}),el('span','Image Edit'),el('small','Image 1 → compare'));
|
||||
this.controls=el('div','','dap-controls');this.side.append(tabs,this.editRow,this.controls);
|
||||
const main=el('main','','dap-main'),toolbar=el('div','','dap-toolbar');this.context=btn('',()=>this.folderBrowser(false),'dap-project','Apri cartella di lavoro');
|
||||
const views=el('div','','dap-views');
|
||||
const slider=this.slider=el('input');slider.type='range';slider.min='0';slider.max='100';slider.step='any';slider.value=String(this.state.density);slider.setAttribute('aria-label','Dimensione delle immagini');
|
||||
slider.oninput=()=>{this.state.density=Number(slider.value);this.applyDensity();this.save();};
|
||||
views.append(ib('single','Una immagine grande',()=>{slider.value='0';slider.oninput();}),slider,ib('grid','Griglia compatta',()=>{slider.value='100';slider.oninput();}));toolbar.append(this.context,views);
|
||||
this.filters=el('div','','dap-filters');this.notice=el('div','','dap-notice');this.notice.setAttribute('role','status');
|
||||
this.galleryViewport=el('div','','dap-gallery-viewport');this.gallery=el('div','','dap-gallery');this.galleryViewport.append(this.gallery);
|
||||
this.totalProgress=el('div','','dap-total-progress');this.totalBar=el('div','','dap-progress-track');this.totalFill=el('i');this.totalBar.append(this.totalFill);this.totalText=el('span');this.totalProgress.append(this.totalBar,this.totalText);this.totalProgress.hidden=true;main.append(toolbar,this.filters,this.notice,this.galleryViewport);layout.append(this.side,main);this.root.append(this.totalProgress,header,layout);
|
||||
this.updateHeader();this.applyDensity();
|
||||
this.resize=new ResizeObserver(()=>this.applyDensity());this.resize.observe(this.galleryViewport);this.root.addEventListener('close',()=>this.resize.disconnect(),{once:true});
|
||||
this.note(this.bridge.preview?'ANTEPRIMA · Immagini dal tuo design · Nessuna richiesta API':'Reference, parametri e cartella pronti.');
|
||||
}
|
||||
applyDensity(){if(!this.gallery)return;const columns=1+3*Number(this.state.density)/100,width=(this.galleryViewport.clientWidth||1400)/columns;this.gallery.style.setProperty('--card-min',Math.max(170,width-18)+'px');this.slider.title=`Dimensione galleria / ${Math.round(width)} px`;}
|
||||
updateHeader(){const s=this.state;this.context.textContent=[s.workspace||this.bridge.catalog?.access?.output_root||'Comfy output / DOGMA / API',safeName(s.project),safeName(s.scene)].filter(Boolean).join(' / ');this.context.title=this.context.textContent;this.imageTab.classList.toggle('active',s.mode==='image');this.videoTab.classList.toggle('active',s.mode==='video');this.editRow.hidden=s.mode==='video';let n=0;try{n=plannedJobs(s).length;}catch{}this.runLabel.textContent=this.busy?'Invio…':'Run';this.runCount.disabled=this.busy;this.runButton.disabled=this.busy||!n||!this.ready;this.updateProgress();this.runButton.title=`Run ×${s.runCount||1} · ${n} generazioni totali, con seed diversi`;this.runButton.setAttribute('aria-label',this.runButton.title);}
|
||||
switchMode(mode){this.state.mode=mode;this.save();this.renderControls();this.updateHeader();this.refreshPrices();}
|
||||
toggle(label,checked,onchange,tag='label'){const control=el(tag,'','dap-toggle'),input=el('input'),track=el('span','','dap-toggle-track');input.type='checkbox';input.checked=!!checked;input.setAttribute('role','switch');input.setAttribute('aria-label',label);input.onchange=()=>onchange(input.checked);control.title=label;track.setAttribute('aria-hidden','true');track.append(el('span','','dap-toggle-knob'));control.append(input,track);return control;}
|
||||
field(parent,name,value,onchange,opts={}){
|
||||
const row=el('label','','dap-field');row.append(el('span',name));let input,control;
|
||||
if(opts.type==='checkbox'){control=this.toggle(name,value,onchange,'span');input=control.querySelector('input');row.classList.add('has-toggle');}
|
||||
else if(opts.choices){input=el('select');for(const choice of [...new Set([...opts.choices.map(String),...(!opts.choices.map(String).includes(String(value))?[String(value)]:[])])]){const o=el('option',choice);o.value=choice;input.append(o);}input.value=String(value);row.classList.add('has-select');}
|
||||
else{input=el('input');input.type=opts.type||'text';if(input.type==='checkbox')input.checked=!!value;else input.value=String(value??'');}
|
||||
input.setAttribute('aria-label',name);if(opts.min!==undefined)input.min=String(opts.min);if(opts.max!==undefined)input.max=String(opts.max);if(opts.step!==undefined)input.step=String(opts.step);if(opts.placeholder)input.placeholder=opts.placeholder;if(opts.readonly)input.readOnly=true;
|
||||
input.onchange=()=>onchange(input.type==='checkbox'?input.checked:input.value);row.append(control||input);
|
||||
if(input.tagName==='INPUT'&&['text','number','color'].includes(input.type)&&!opts.readonly)input.oninput=()=>input.onchange();
|
||||
if(!opts.readonly&&(opts.choices||opts.type==='number')){
|
||||
const step=direction=>{if(opts.choices){input.selectedIndex=(input.selectedIndex+direction+input.options.length)%input.options.length;}else{const next=Number(input.value||0)+direction*Number(opts.step||1);input.value=String(Math.min(opts.max??Infinity,Math.max(opts.min??-Infinity,next)));}input.onchange();};
|
||||
const previous=ib('arrow','Riduci / precedente '+name,e=>step(-1),'dap-field-step'),next=ib('arrow','Aumenta / successivo '+name,e=>step(1),'dap-field-step next');
|
||||
previous.addEventListener('click',e=>e.preventDefault());next.addEventListener('click',e=>e.preventDefault());row.prepend(previous);row.append(next);
|
||||
}
|
||||
parent.append(row);return input;
|
||||
}
|
||||
renderControls(){
|
||||
const c=this.controls,s=this.state;c.replaceChildren();
|
||||
const refs=el('section','','dap-section');refs.append(el('div','REFERENCES','dap-label'));this.refs=el('div','','dap-refs');refs.append(this.refs);this.renderRefs();
|
||||
const prompt=el('section','','dap-section dap-prompt');prompt.append(el('div','PROMPT','dap-label'));const wrap=el('div','','dap-prompt-wrap'),area=el('textarea');area.value=s.prompts[s.mode]||'';area.setAttribute('aria-label','Prompt');area.placeholder='Scrivi il prompt…';area.oninput=()=>{s.prompts[s.mode]=area.value;this.save();};
|
||||
const resize=el('div','','dap-resize-handle');resize.title='Trascina per ingrandire il prompt';let start=null;
|
||||
resize.onpointerdown=e=>{e.preventDefault();start={y:e.clientY,height:area.offsetHeight};resize.setPointerCapture(e.pointerId);};resize.onpointermove=e=>{if(start)area.style.height=Math.max(90,start.height+e.clientY-start.y)+'px';};resize.onpointerup=resize.onpointercancel=()=>start=null;wrap.append(area,resize);prompt.append(wrap);
|
||||
const workSection=el('details','','dap-section dap-work');workSection.open=!!s.workExpanded;workSection.ontoggle=()=>{s.workExpanded=workSection.open;this.save();};const workLabel=el('div','FILENAME / WORKSPACE','dap-label dap-work-label');const workTitle=el('summary');this.namePreview=el('span',this.filenamePreview(),'dap-filename-preview');workTitle.append(this.namePreview,icon('chevron'));const work=el('div');workSection.append(workTitle,work);
|
||||
this.field(work,'FILENAME',s.filename,v=>{s.filename=v;this.save();this.namePreview.textContent=this.filenamePreview();},{placeholder:'DOGMA'});
|
||||
this.field(work,'PROJECT',s.project,v=>{s.project=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
|
||||
this.field(work,'SCENE',s.scene,v=>{s.scene=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
|
||||
const date=el('div','','dap-date-row'),datePicker=el('input');datePicker.type='date';const code=s.date||todayCode();datePicker.value=`20${code.slice(4,6)}-${code.slice(2,4)}-${code.slice(0,2)}`;datePicker.setAttribute('aria-label','Data del filename');datePicker.onchange=()=>{const [year,month,day]=datePicker.value.split('-');if(!year)return;s.date=day+month+year.slice(-2);s.dateMode='manual';this.save();this.namePreview.textContent=this.filenamePreview();};date.append(this.toggle('Aggiungi data al filename',s.appendDate,v=>{s.appendDate=v;s.date ||= todayCode();this.save();this.namePreview.textContent=this.filenamePreview();}),el('span','Aggiungi data'),datePicker);work.append(date);
|
||||
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));const folderRow=el('div','','dap-workspace-row'),explorer=btn('Esplora file',()=>this.openWorkspaceExplorer(),'dap-workspace-explorer','Apri in Esplora file');explorer.append(icon('external'));folderRow.append(choose,explorer);work.append(folderRow);
|
||||
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of families(s))models.append(this.model(f));
|
||||
if(s.mode==='video'){const choice=el('section','','dap-video-choice');choice.append(el('div','WORKFLOW VIDEO','dap-label'));for(const [key,label] of [['reference','Ref → Video'],['frames','First / Last frame']]){const b=btn(label,()=>{s.models.seedance.engine=key;this.save();this.renderControls();this.refreshPrices();},key===s.models.seedance.engine?'active':'');choice.append(b);}c.append(choice);}
|
||||
c.append(refs,prompt,workLabel,workSection,models);
|
||||
}
|
||||
filenamePreview(){return [...titleParts(this.state),'MODEL',this.state.mode==='video'?'00001.mp4':'00001.png'].filter(Boolean).join('_');}
|
||||
renderRefs(){
|
||||
if(!this.refs)return;this.refs.replaceChildren();
|
||||
const visible=visibleReferences(this.state);
|
||||
visible.forEach((r,i)=>{
|
||||
const tile=el('article','','dap-ref');tile.classList.toggle('disabled',!r.enabled);tile.dataset.ref=String(i);
|
||||
const media=el(r.kind==='video'?'video':'img');media.src=r.processedPreview?this.bridge.view(r.processedPreview):r.preview||this.bridge.view(r.file);media.draggable=false;if(r.kind==='video'){media.muted=true;media.preload='metadata';media.onpointerenter=()=>media.play().catch(()=>{});media.onpointerleave=()=>media.pause();}else media.alt=`Image ${i+1}`;
|
||||
media.onclick=()=>r.kind==='video'?this.referenceVideo(r):referenceEditor(this,r);
|
||||
media.onerror=()=>tile.classList.add('missing');
|
||||
const tools=el('div','','dap-ref-tools');tools.append(this.toggle(`Attiva reference ${i+1}`,r.enabled,v=>{r.enabled=v;this.save();this.renderRefs();this.refreshPrices();}));
|
||||
if(r.kind==='image')tools.append(ib('edit',`Modifica reference ${i+1}`,()=>referenceEditor(this,r)));
|
||||
else tools.append(ib('play',`Apri video reference ${i+1}`,()=>this.referenceVideo(r)));
|
||||
if(i>0)tools.append(ib('arrow',`Sposta prima reference ${i+1}`,()=>{const a=this.state.references.indexOf(visible[i-1]),b=this.state.references.indexOf(r);[this.state.references[a],this.state.references[b]]=[r,visible[i-1]];this.save();this.renderRefs();}));
|
||||
tools.append(ib('close',`Rimuovi reference ${i+1}`,()=>{this.state.references.splice(this.state.references.indexOf(r),1);this.save();this.renderRefs();this.refreshPrices();}));
|
||||
tile.append(media,el('span',`${String(i+1).padStart(2,'0')} / ${r.kind==='video'?'VIDEO':'IMAGE'}`,'dap-ref-order'),tools);
|
||||
if(r.process?.enabled)tile.append(el('span','EDIT','dap-ref-edited'));
|
||||
if(this.state.mode==='video'&&this.state.models.seedance.engine==='frames'&&r.kind==='image'){
|
||||
const select=el('select','','dap-ref-role');select.setAttribute('aria-label',`Ruolo reference ${i+1}`);for(const [key,text] of [['first','First frame'],['last','Last frame']]){const o=el('option',text);o.value=key;select.append(o);}select.value=r.role||'reference';select.onchange=()=>{r.role=select.value;this.save();};tile.append(select);
|
||||
}
|
||||
this.refs.append(tile);
|
||||
});
|
||||
const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames',mixed=this.state.mode==='video'&&!frames;const add=ib('plus',mixed?'Aggiungi immagini o video':'Aggiungi immagine',()=>this.pickReferences(),'dap-add');const hoverIcon=icon(mixed?'media':'image');hoverIcon.classList.add('dap-add-hover');add.append(hoverIcon);if(!frames||visible.length<2)this.refs.append(add);
|
||||
}
|
||||
pickReferences(replace=null){const i=el('input');i.type='file';i.accept=this.state.mode==='video'&&this.state.models.seedance.engine!=='frames'?'image/*,video/*':'image/*';i.multiple=!replace;i.hidden=true;this.root.append(i);i.onchange=()=>{this.addReferences([...i.files],replace);i.remove();};i.addEventListener('cancel',()=>i.remove(),{once:true});i.click();}
|
||||
async addReferences(files,replace=null){try{this.note('Caricamento reference…');for(const file of files){if(!/^(image|video)\//.test(file.type))throw new Error('Scegli immagini o video.');const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames';if(file.type.startsWith('video/')&&(this.state.mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');if(frames&&!replace&&visibleReferences(this.state).length>=2)throw new Error('First / Last frame accetta due immagini.');const uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:frames?(replace?.role|| (visibleReferences(this.state).some(r=>r.role==='first')?'last':'first')):'reference',process:{enabled:false,mask:false,maskMode:'edit',source:'paint',flip:false,invert:false,crop:false,fillHoles:false,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#ff00ff'}};if(replace){const at=this.state.references.indexOf(replace);this.state.references.splice(at,1,r);}else this.state.references.push(r);}this.save();this.renderRefs();this.refreshPrices();this.note('Reference aggiornate. L’ordine è quello mostrato.');}catch(e){this.note(e.message,true);}}
|
||||
referenceVideo(ref){openViewer(this,{job:{kind:'video',label:ref.file,study:true},file:{url:ref.preview||this.bridge.view(ref.file)},index:0});}
|
||||
model(f){
|
||||
const m=this.state.models[f.key],wrap=el('div','','dap-model'),row=el('div','','dap-model-head');wrap.setAttribute('role','group');wrap.setAttribute('aria-label',f.name);
|
||||
const toggle=this.toggle(`Attiva ${f.name}`,m.enabled,v=>{m.enabled=v;wrap.classList.toggle('enabled',v);this.save();this.updateHeader();});wrap.classList.toggle('enabled',m.enabled);
|
||||
const details=el('details');details.open=!!m.expanded;details.ontoggle=()=>{m.expanded=details.open;this.save();};
|
||||
const summary=el('summary');this.priceLabels ||= new Map();const price=el('small','— CREDITS / '+(f.key==='seedance'?'RUN':'IMAGE'));this.priceLabels.set(f.key,price);summary.append(el('span',f.name),price,icon('chevron'));details.append(summary);
|
||||
const body=el('div','','dap-model-body');
|
||||
this.field(body,'QUANTITY',m.quantity,v=>{m.quantity=Number(v);this.save();this.updateHeader();},{type:'number',min:1,max:64});
|
||||
body.append(el('div','Richieste in parallelo · Seed diversi','dap-field-hint'));
|
||||
|
||||
const values=m.engine==='frames'?m.frames:m.parameters;
|
||||
const nativeSpecs=this.bridge.parameterSpecs?.(this.state,f);const entries=nativeSpecs&&Object.keys(nativeSpecs).length?Object.keys(nativeSpecs).map(key=>[key,values[key]??nativeSpecs[key][1]?.default??choicesFor(nativeSpecs[key])?.[0]??'']):Object.entries(values);
|
||||
for(const [key,value] of entries){
|
||||
if(['prompt','model.prompt','system_prompt','seed','model.seed','n'].includes(key)||key.startsWith('control_after_generate')||key.endsWith('asset_id'))continue;
|
||||
const opts={};if(enumValues[key])opts.choices=enumValues[key];
|
||||
if(key==='model'){if(f.key==='nano')opts.choices=['gemini-3-pro-image-preview','Nano Banana 2 (Gemini 3.1 Flash Image)'];else opts.readonly=true;}
|
||||
if(key==='resolution'&&f.key==='flux')opts.choices=['0.75K','1K','1.5K','2K','4K'];
|
||||
if(typeof value==='boolean')opts.type='checkbox';if(typeof value==='number'){opts.type='number';opts.min=key==='model.duration'?4:0;opts.max=key==='model.duration'?30:8594;}
|
||||
const spec=this.bridge.inputSpec?.(this.state,f,key);
|
||||
if(spec){const info=spec[1]||{};if(Array.isArray(spec[0]))opts.choices=spec[0];else if(choicesFor(spec))opts.choices=choicesFor(spec);if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
|
||||
if(opts.choices){opts.choices=sortedChoices(key,opts.choices);delete opts.readonly;}
|
||||
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();},opts);
|
||||
}
|
||||
if(values.system_prompt!==undefined){const advanced=el('details','','dap-advanced');advanced.append(el('summary','SYSTEM PROMPT'));const text=el('textarea');text.value=values.system_prompt;text.setAttribute('aria-label',f.name+' system prompt');text.oninput=()=>{values.system_prompt=text.value;this.save();};advanced.append(text);body.append(advanced);}
|
||||
if(f.key==='seedance')body.append(el('div',m.engine==='frames'?'Usa un First frame, un Last frame o entrambi. Sono accettate soltanto immagini.':'Usa immagini o video come reference. In Edit la durata segue il video sorgente.','dap-field-hint'));
|
||||
details.append(body);row.append(toggle,details);wrap.append(row);return wrap;
|
||||
}
|
||||
async refreshCredits(){if(this.creditBusy||this.closed)return;this.creditBusy=true;try{const result=await this.bridge.credits();if(!this.closed){this.credit.textContent=result.text;this.credit.title=result.title;}}catch{}finally{this.creditBusy=false;}}
|
||||
refreshPrices(){if(this.closed)return;for(const f of families(this.state)){const text=this.bridge.price?.(this.state,f);const node=this.priceLabels?.get(f.key);if(node&&text){node.textContent=text;node.title='Stima calcolata dalle stesse regole di Comfy per questi parametri';}}}
|
||||
allResults(){const map=new Map;for(const r of [...this.library,...this.state.results])map.set(r.id,r);return orderResults([...map.values()]);}
|
||||
renderFilters(){
|
||||
if(!this.filters)return;const s=this.state,all=this.allResults();this.filters.replaceChildren();
|
||||
const model=el('details','','dap-filter-models');const summary=el('summary');summary.append(icon('filter'),el('span',s.filters.models.length?s.filters.models.map(k=>ALL_FAMILIES.find(f=>f.key===k)?.name||k).join(', '):'Tutti i modelli'),icon('chevron'));const menu=el('div','','dap-filter-menu');
|
||||
const any=btn('Tutti i modelli',()=>{s.filters.models=[];this.save();this.renderFilters();this.renderGallery();});menu.append(any);
|
||||
for(const f of ALL_FAMILIES){const item=el('label'),check=el('input');check.type='checkbox';check.checked=s.filters.models.includes(f.key);check.onchange=()=>{s.filters.models=check.checked?[...s.filters.models,f.key]:s.filters.models.filter(k=>k!==f.key);this.save();this.renderGallery();summary.querySelector('span').textContent=s.filters.models.length?s.filters.models.map(k=>ALL_FAMILIES.find(f=>f.key===k)?.name).join(', '):'Tutti i modelli';};item.append(check,el('span',f.name));menu.append(item);}model.append(summary,menu);this.filters.append(model);
|
||||
const select=(name,current,choices,change)=>{const box=el('label','','dap-filter');box.append(el('span',name));const input=el('select');input.setAttribute('aria-label',name);for(const [value,text] of choices){const option=el('option',text);option.value=value;input.append(option);}input.value=current;input.onchange=()=>{change(input.value);this.save();this.renderFilters();this.renderGallery();};input.style.paddingLeft=(name.length*.6+1.8)+'em';box.append(input,icon('chevron'));this.filters.append(box);};
|
||||
const projects=[...new Set(all.map(r=>r.project||''))].sort();select('Progetto',s.filters.project,[['*','Tutti i progetti'],...projects.map(p=>[p,p||'Senza progetto'])],v=>{s.filters.project=v;s.filters.scene='*';});
|
||||
const scenes=[...new Set(all.filter(r=>s.filters.project==='*'||(r.project||'')===s.filters.project).map(r=>r.scene||''))].sort();select('Scena',s.filters.scene,[['*','Tutte le scene'],...scenes.map(v=>[v,v||'Senza scena'])],v=>s.filters.scene=v);
|
||||
select('Output',s.filters.kind,[['all','Immagini e video'],['image','Immagini'],['video','Video']],v=>s.filters.kind=v);
|
||||
const ws=[...new Set(all.map(r=>r.workspace||''))];if(ws.length>1)select('Cartella',s.filters.workspace,[['*','Tutte le cartelle'],...ws.map(v=>[v,v.split(/[\\/]/).filter(Boolean).at(-1)||'Comfy output'])],v=>s.filters.workspace=v);
|
||||
const errors=el('label','','dap-error-filter');errors.append(this.toggle('Mostra o nascondi generazioni fallite',!s.filters.hideErrors,checked=>{s.filters.hideErrors=!checked;this.save();this.renderGallery();},'span'),el('span','Mostra errori'));this.filters.append(errors,ib('refresh','Aggiorna libreria',()=>this.refreshLibrary()));
|
||||
}
|
||||
renderGallery(){
|
||||
const scroll=this.galleryViewport?.scrollTop||0,version=this.galleryVersion=(this.galleryVersion||0)+1;this.gallery.replaceChildren();this.cards.clear();const list=filterResults(this.allResults(),this.state.filters);
|
||||
if(!list.length){const empty=el('div','','dap-empty');empty.append(el('span','DOGMA / OUTPUT'),el('h2',this.allResults().length?'Nessun risultato con questi filtri.':'Pronto per il prossimo frame.'),el('p',this.allResults().length?'Cambia progetto, scena o modelli per vedere gli altri output.':'Scegli i modelli e la quantità. Run avvia le richieste API in parallelo.'));this.gallery.append(empty);return;}
|
||||
const pending=list.flatMap(job=>(job.images?.length?job.images:[null]).map((file,index)=>({job,file,index})));let offset=0;
|
||||
const append=()=>{if(this.closed||version!==this.galleryVersion)return;const fragment=document.createDocumentFragment();for(const item of pending.slice(offset,offset+40))fragment.append(this.card(item.job,item.file,item.index));this.gallery.append(fragment);offset+=40;this.updateCards();this.updateSelection();if(offset<pending.length)requestAnimationFrame(append);};append();this.galleryViewport.scrollTop=scroll;this.applyDensity();
|
||||
}
|
||||
card(job,file,index){
|
||||
const card=el('article','','dap-card');card.dataset.job=job.id;const f=ALL_FAMILIES.find(f=>f.key===job.family),title=job.label||f?.name||'Output';
|
||||
if(file){
|
||||
const media=el('div','','dap-card-media');
|
||||
if(job.kind==='video'){
|
||||
const video=el('video');video.src=this.bridge.view(file);video.muted=true;video.preload='metadata';video.loop=true;video.playsInline=true;media.append(video);
|
||||
const duration=el('span','','dap-video-duration');video.onloadedmetadata=()=>{duration.textContent=Number.isFinite(video.duration)?`${Math.floor(video.duration/60)}:${String(Math.floor(video.duration%60)).padStart(2,'0')}`:'';};media.append(icon('play'),duration);
|
||||
media.onpointerenter=()=>{video.play().then(()=>media.classList.add('playing')).catch(()=>{});};media.onpointerleave=()=>{video.pause();media.classList.remove('playing');};
|
||||
}else{const base=job.imageEdit&&job.baseReference?(job.baseReference.comparePreview||this.bridge.view(job.baseReference.processedPreview||job.baseReference.file)):null;const comparison=hoverCompare(media,this.bridge.view(file),base);comparison.image.loading='lazy';comparison.image.decoding='async';comparison.image.alt=title;}
|
||||
media.onclick=()=>openViewer(this,{job,file,index});media.tabIndex=0;media.setAttribute('role','button');media.setAttribute('aria-label','Apri '+title);media.onkeydown=e=>{if(e.key==='Enter')media.click();};card.append(media);
|
||||
const tools=el('div','','dap-card-tools'),item={id:job.id+':'+index,job,file,index};
|
||||
const select=btn('A\\B',()=>this.selectCompare(item),'dap-icon-button dap-ab','Scegli immagine o video per il confronto A/B');select.dataset.compare=item.id;
|
||||
tools.append(select,ib('plus','Usa come reference',()=>this.reuse(file,job.kind)),ib('prompt','Leggi e copia prompt',()=>this.showPrompt(job)),ib('download','Scarica file',()=>this.downloadImage(file)));card.append(tools);
|
||||
if(job.study)card.append(el('span','DESIGN REFERENCE','dap-study'));
|
||||
}else{
|
||||
card.classList.add('pending');const logo=el('video','','dap-loading-logo');logo.src=this.bridge.loadingLogo();logo.muted=true;logo.loop=true;logo.autoplay=true;logo.playsInline=true;logo.setAttribute('aria-label','Generazione in corso');
|
||||
const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));const error=el('div','','dap-error-content');error.append(el('span','ERRORE'),el('p',job.error||''));card.append(logo,track,error);
|
||||
}
|
||||
const footer=el('footer','','dap-card-footer'),caption=el('span',title+(job.index!==undefined?' / '+(job.index+1):'')+(file?' - '+savedFilename(job,index):''),'dap-result-name');caption.title=caption.textContent;
|
||||
footer.append(caption);if(!file)footer.append(el('span','','dap-job-state'));footer.append(el('span',[job.project,job.scene].filter(Boolean).join(' / '),'dap-card-tags'),el('span','','dap-elapsed'));card.append(footer);
|
||||
if(job.warning)card.append(el('p',job.warning,'dap-card-error'));
|
||||
card.append(el('span','','dap-error-countdown'));
|
||||
if(!this.cards.has(job.id))this.cards.set(job.id,[]);this.cards.get(job.id).push(card);return card;
|
||||
}
|
||||
updateCards(){
|
||||
this.updateProgress();let expired=false;
|
||||
for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){
|
||||
const p=this.jobProgress(job),bar=card.querySelector('.dap-card-progress>i');if(bar){bar.style.width=p.percent+'%';bar.parentElement.classList.toggle('indeterminate',!!p.indeterminate);bar.parentElement.title=p.label;}
|
||||
const status=card.querySelector('.dap-job-state');if(status)status.textContent=({submitting:'Invio',queued:'In attesa',running:'Generazione API',failed:'Errore',cancelled:'Interrotta',missing:'Output assente'})[job.status]||job.status;
|
||||
card.classList.toggle('stopped',terminal.has(job.status));card.classList.toggle('failed',['failed','missing'].includes(job.status));
|
||||
const elapsed=card.querySelector('.dap-elapsed'),seconds=job.started?Math.max(0,Math.floor(((job.finished||Date.now())-job.started)/1000)):null;elapsed.textContent=job.study?'LAYOUT':seconds!==null?seconds+'s'+(!terminal.has(job.status)&&p.expected?'/~'+Math.round(p.expected)+'s':''):'';
|
||||
const error=card.querySelector('.dap-error-content p');if(error)error.textContent=job.error||'';
|
||||
const countdown=card.querySelector('.dap-error-countdown'),remaining=Math.ceil(((job.errorVisibleUntil||0)-Date.now())/1000);countdown.textContent=this.state.filters.hideErrors&&['failed','missing'].includes(job.status)&&remaining>0?`Si nasconde tra ${remaining}s`:'';
|
||||
if(this.state.filters.hideErrors&&['failed','missing'].includes(job.status)&&remaining<=0)expired=true;
|
||||
const logo=card.querySelector('.dap-loading-logo');if(logo&&terminal.has(job.status))logo.pause();
|
||||
}
|
||||
if(expired)this.renderGallery();this.updateSelection();
|
||||
}
|
||||
selectCompare(item){
|
||||
const at=this.selection.findIndex(x=>x.id===item.id);
|
||||
if(at>=0)this.selection.splice(at,1);else{if(this.selection.length===2)this.selection=[];this.selection.push(item);}
|
||||
this.updateSelection();if(this.selection.length===2){this.note('Confronto A/B · seleziona un’altra immagine per iniziare una nuova coppia.');this.compare();}else this.note(this.selection.length?'A selezionata · scegli il secondo risultato per aprire il confronto.':'Selezione confronto rimossa.');
|
||||
}
|
||||
updateSelection(){for(const b of this.root?.querySelectorAll('[data-compare]')||[]){const n=this.selection.findIndex(x=>x.id===b.dataset.compare);b.textContent=n<0?'A\\B':n===0?'A':'B';b.classList.toggle('selected',n>=0);b.setAttribute('aria-pressed',String(n>=0));}}
|
||||
showPrompt(job){const box=this.modalBox('PROMPT','dap-prompt-modal',true),text=el('textarea');text.value=job.prompt||'Prompt non disponibile per questo output.';text.readOnly=true;text.setAttribute('aria-label','Prompt originale');box.append(text,btn('Copia prompt',async e=>{const button=e.currentTarget;try{await navigator.clipboard.writeText(text.value);button.textContent='Copiato';}catch{text.select();}},'dap-outline'));}
|
||||
async openWorkspaceExplorer(){try{const path=this.state.workspace||this.bridge.catalog?.access?.output_root;await this.bridge.explorer(path);}catch(e){this.note(e.message,true);}}
|
||||
modalBox(title,cls='',nested=false){
|
||||
this.modals ||= [];if(!nested)for(const box of [...this.modals].reverse())box.close();const dialog=this.modal=el('dialog','','dap-modal '+cls);dialog.setAttribute('aria-label',title);const header=el('header');header.append(el('span',title),ib('close','Chiudi',()=>dialog.close()));dialog.append(header);this.root.append(dialog);
|
||||
let down=false;dialog.addEventListener('pointerdown',e=>down=e.target===dialog);dialog.addEventListener('click',e=>{if(down&&e.target===dialog)dialog.close();down=false;});
|
||||
dialog.addEventListener('cancel',e=>e.stopPropagation());dialog.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();dialog.close();}});dialog.addEventListener('close',()=>{dialog.remove();this.modals=this.modals.filter(d=>d!==dialog);this.modal=this.modals.at(-1)||null;});this.modals.push(dialog);dialog.tabIndex=-1;dialog.showModal();dialog.focus({preventScroll:true});return dialog;
|
||||
}
|
||||
compare(){if(this.selection.length===2)openViewer(this,this.selection[0],this.selection[1]);}
|
||||
async openOutput(job,index){try{const target=await this.bridge.openOutput(job.id,index);await this.folderBrowser(false,target.path,target.filename);}catch(e){this.note(e.message,true);if(this.modal)this.modal.append(el('p',e.message,'dap-operation-note'));}}
|
||||
async downloadImage(file){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const url=URL.createObjectURL(await r.blob());this.urls.add(url);const a=el('a');a.href=url;a.download=file.filename||'DOGMA_output';a.click();}catch(e){this.note(e.message,true);}}
|
||||
async reuse(file,kind){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const blob=await r.blob();await this.addReferences([new File([blob],file.filename||'DOGMA_reference.png',{type:blob.type|| (kind==='video'?'video/mp4':'image/png')})]);}catch(e){this.note(e.message,true);}}
|
||||
async chooseWorkspace(){return this.folderBrowser(true);}
|
||||
async folderBrowser(choose=true,initial=null,selected=''){
|
||||
const box=this.modalBox(choose?'SCEGLI CARTELLA DI LAVORO':'CARTELLA / FILE','dap-folder-modal'),bar=el('div','','dap-folder-navigation'),address=el('input'),list=el('div','','dap-folder-list'),footer=el('div','','dap-folder-footer'),error=el('p','','dap-operation-note');address.setAttribute('aria-label','Percorso cartella');bar.append(address);box.append(bar,list,error,footer);
|
||||
let navigation=0,typing;const render=async path=>{const token=++navigation;error.textContent='';try{const data=await this.bridge.folders(path);if(!box.isConnected||token!==navigation)return;address.value=data.path;list.replaceChildren();footer.replaceChildren();
|
||||
if(data.parent)list.append(btn('↑ Cartella superiore',()=>render(data.parent),'dap-outline'));
|
||||
for(const root of data.roots||[]){const b=ib('folder',root.name,()=>render(root.path));b.append(el('span',root.name));list.append(b);}
|
||||
for(const dir of data.directories){const b=ib('folder',dir.name,()=>render(dir.path));b.append(el('span',dir.name));list.append(b);}
|
||||
for(const file of data.files||[]){const row=el('div',file.name,'dap-folder-file'+(file.name===selected?' selected':''));if(file.name===selected)row.setAttribute('aria-current','true');list.append(row);}
|
||||
const name=el('input');name.placeholder='Nome nuova cartella';name.setAttribute('aria-label','Nome nuova cartella');footer.append(name,btn('Crea cartella',async()=>{try{const d=await this.bridge.mkdir(data.path,name.value);await render(d.path);}catch(e){error.textContent=e.message;}},'dap-outline'));
|
||||
if(choose)footer.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;for(const record of result.records||[]){const existing=this.state.results.find(j=>j.id===record.id);if(existing)Object.assign(existing,record);}this.library=[...this.library.filter(r=>!(result.records||[]).some(x=>x.id===r.id)),...(result.records||[])];this.save();this.renderFilters();this.renderGallery();box.close();this.renderControls();this.updateHeader();this.note('Cartella di lavoro selezionata.');}catch(e){error.textContent=e.message;}},'dap-primary'));
|
||||
list.querySelector('[aria-current]')?.scrollIntoView({block:'center'});
|
||||
}catch(e){if(token===navigation)error.textContent=e.message;}};address.oninput=()=>{clearTimeout(typing);navigation++;typing=setTimeout(()=>render(address.value.trim().replace(/^"|"$/g,'')),650);};address.onkeydown=e=>{if(e.key==='Enter'){e.preventDefault();clearTimeout(typing);render(address.value.trim().replace(/^"|"$/g,''));}};box.addEventListener('close',()=>{clearTimeout(typing);navigation++;});await render(initial??this.state.workspace);
|
||||
}
|
||||
jobProgress(job){
|
||||
if(terminal.has(job.status))return {percent:job.status==='completed'?100:job.stoppedProgress??Math.min(99,(job.progress||0)*100),label:job.status,remaining:0};
|
||||
if(Number.isFinite(job.progress)&&job.progress>0)return {percent:Math.min(99,job.progress*100),label:Math.round(job.progress*100)+'% · avanzamento Comfy',remaining:job.progress<1?Math.max(0,Math.round((Date.now()-job.started)/1000*(1-job.progress)/job.progress)):0};
|
||||
const samples=this.allResults().filter(j=>j.family===job.family&&j.status==='completed'&&j.finished>j.started&&!j.study).slice(0,8).map(j=>(j.finished-j.started)/1000);
|
||||
if(!samples.length)return {percent:15,indeterminate:true,label:'Tempo trascorso · stima disponibile dopo le prime generazioni',remaining:null};
|
||||
const expected=samples.reduce((a,b)=>a+b,0)/samples.length,elapsed=(Date.now()-job.started)/1000;
|
||||
return {expected,percent:Math.min(94,100*elapsed/expected),remaining:Math.max(0,Math.round(expected-elapsed)),label:elapsed<expected?'~'+Math.round(expected-elapsed)+'s rimanenti · stima':'Finalizzazione · stima superata'};
|
||||
}
|
||||
updateProgress(){
|
||||
if(!this.totalProgress)return;const jobs=this.state.results.filter(j=>!terminal.has(j.status)),ids=new Set(jobs.map(j=>j.batch));const batch=this.state.results.filter(j=>ids.has(j.batch));
|
||||
this.stopButton.disabled=!jobs.length&&!this.busy;this.totalProgress.hidden=!jobs.length;if(!jobs.length)return;
|
||||
const points=batch.map(j=>this.jobProgress(j));this.totalFill.style.width=points.reduce((s,p)=>s+p.percent,0)/points.length+'%';this.totalBar.classList.toggle('indeterminate',points.some(p=>p.indeterminate));
|
||||
const known=jobs.map(j=>this.jobProgress(j).remaining);this.totalText.textContent=`${batch.filter(j=>terminal.has(j.status)).length} / ${batch.length} completate · `+(known.every(n=>n!==null)?`~${Math.max(...known)}s rimanenti · stima`:'Calcolo in corso · tempo residuo non ancora disponibile');
|
||||
}
|
||||
async stop(){
|
||||
this.stopRequested=true;const jobs=this.state.results.filter(j=>!terminal.has(j.status));const ids=[...new Set(jobs.map(j=>j.promptId).filter(Boolean))];this.stopButton.disabled=true;this.note('Interruzione richiesta…');
|
||||
const results=await Promise.allSettled(ids.map(id=>this.bridge.cancel(id)));for(let i=0;i<ids.length;i++)if(results[i].status==='fulfilled')for(const job of jobs.filter(j=>j.promptId===ids[i]))if(!terminal.has(job.status)){job.stoppedProgress=this.jobProgress(job).percent;job.status='cancelled';job.finished=Date.now();}
|
||||
this.save();this.updateCards();this.note(results.some(r=>r.status==='rejected')?'Una richiesta di stop non è riuscita. Riprova.':'Stop inviato a Comfy. Le richieste già completate dal servizio possono essere addebitate.',results.some(r=>r.status==='rejected'));
|
||||
}
|
||||
async refreshLibrary(){if(!this.bridge.library||this.closed)return;try{this.library=await this.bridge.library();if(this.closed)return;for(const r of this.library.filter(r=>r.imported)){const existing=this.state.results.find(j=>j.id===r.id);if(existing)Object.assign(existing,r);}this.renderFilters();this.renderGallery();}catch(e){this.note('Libreria temporaneamente non disponibile.',true);}}
|
||||
async run(){
|
||||
if(this.busy)return;try{validateState(this.state);}catch(e){this.note(e.message,true);return;}
|
||||
this.stopRequested=false;this.busy=true;this.updateHeader();const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
|
||||
const jobs=plannedJobs(snapshot).map((p,ordinal)=>({...p,id:crypto.randomUUID(),batch,started,batchStarted:started,ordinal,status:'submitting',images:[]}));
|
||||
try{
|
||||
const primary=activeReferences(snapshot).find(r=>r.kind==='image');
|
||||
for(const ref of activeReferences(snapshot).filter(r=>r.kind==='image'&&r.process?.enabled)){
|
||||
if((ref.process.source==='prompt'&&ref.process.mask)||(ref===primary&&snapshot.mode==='image'&&snapshot.imageEdit)){
|
||||
this.note(ref.process.source==='prompt'?'Preparazione maschera SAM3…':'Preparazione Image 1…');const prepared=await this.bridge.previewReference(ref,ref.process);ref.processedPreview=prepared.file;
|
||||
if(prepared.maskFile)Object.assign(ref.process,{maskFile:prepared.maskFile,samSource:prepared.samSource,samPrompt:prepared.samPrompt,samSegment:prepared.samSegment});
|
||||
}
|
||||
}
|
||||
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647);
|
||||
this.note('Controllo reference e nodi…');await this.bridge.check(snapshot,compiled);if(this.closed||this.stopRequested)return;
|
||||
this.state.results.push(...jobs);this.save();this.renderFilters();this.renderGallery();this.galleryViewport.scrollTop=0;
|
||||
const promptId=await this.bridge.queue(compiled,batch,this.state);for(const job of jobs){job.promptId=promptId;if(job.status==='submitting')job.status='queued';}for(const [name,d] of this.pendingEvents||[])this.event(name,d);this.pendingEvents=[];if(this.stopRequested)await this.stop();this.save();this.updateCards();this.note(`${jobs.length} generazioni indipendenti inviate in un unico batch parallelo.`);
|
||||
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.stoppedProgress=this.jobProgress(j).percent;j.status='failed';j.error=e.message;j.finished=Date.now();j.errorVisibleUntil=Date.now()+5000;}}this.save();this.updateCards();this.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
|
||||
}
|
||||
event(name,d){
|
||||
if(!d?.prompt_id)return;const jobs=this.state.results.filter(j=>j.promptId===d.prompt_id);if(!jobs.length){this.pendingEvents ||= [];if(this.busy&&this.pendingEvents.length<200)this.pendingEvents.push([name,d]);return;}
|
||||
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)){if(n.state==='running')j.status='running';if(n.max>0&&n.value>0)j.progress=n.value/n.max;}}}
|
||||
if(name==='progress'){const j=jobs.find(x=>x.generator===String(d.node));if(j&&d.max>0){j.progress=d.value/d.max;j.status='running';}}
|
||||
if(name==='executing'&&d.node){const j=jobs.find(x=>x.generator===String(d.node));if(j)j.status='running';}
|
||||
if(name==='executed'){
|
||||
const job=jobs.find(x=>x.output===String(d.node));if(job&&d.output?.images){const record=d.output.dogma_records?.[0];Object.assign(job,record||{images:d.output.images,status:'completed',finished:Date.now()});this.renderFilters();this.renderGallery();}
|
||||
}
|
||||
if(name==='execution_error'){const failed=jobs.find(j=>j.generator===String(d.node_id)||j.output===String(d.node_id));for(const job of jobs)if(!terminal.has(job.status)){job.stoppedProgress=this.jobProgress(job).percent;job.status=job===failed?'failed':'cancelled';if(job===failed)job.errorVisibleUntil=Date.now()+5000;job.error=job===failed?d.exception_message:'Batch arrestato da Comfy. Nessun retry automatico.';job.finished=Date.now();}this.note(d.exception_message||'Errore nel batch.',true);}
|
||||
if(name==='execution_interrupted')for(const job of jobs)if(!terminal.has(job.status)){job.stoppedProgress=this.jobProgress(job).percent;job.status='cancelled';job.finished=Date.now();}
|
||||
if(name==='execution_success'){this.recover();this.refreshCredits();this.refreshLibrary();}this.save();this.updateCards();
|
||||
}
|
||||
async recover(){
|
||||
if(this.recovering||!this.bridge.history||this.closed)return;this.recovering=true;
|
||||
try{const history=await this.bridge.history();if(this.closed)return;let changed=false;
|
||||
for(const record of Object.values(history||{})){
|
||||
const meta=record.prompt?.[3]?.extra_pnginfo?.workflow?.extra?.dogma_api_batch;if(meta?.session!==this.state.session)continue;
|
||||
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}if(job.imported)continue;job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.stoppedProgress=this.jobProgress(job).percent;job.status=record.status.status_str==='success'?'missing':'failed';job.errorVisibleUntil=Date.now()+5000;job.finished=Date.now();job.error='Comfy non ha restituito questo output.';}}
|
||||
}
|
||||
this.save();if(changed){this.renderFilters();this.renderGallery();}else this.updateCards();
|
||||
}catch{this.note('La cronologia non è momentaneamente disponibile. I batch già accettati continuano in Comfy.',true);}finally{this.recovering=false;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { icon } from './dogma_api_icons.js?v=1.0.56';
|
||||
import {savedFilename} from './dogma_api_core.js?v=1.0.56';
|
||||
|
||||
export async function copyFullImage(url){
|
||||
if(!navigator.clipboard?.write||!globalThis.ClipboardItem)throw new Error('La copia immagini richiede HTTPS o localhost. Puoi scaricare il file a piena risoluzione.');
|
||||
const png=(async()=>{const response=await fetch(url);if(!response.ok)throw new Error('Immagine non disponibile.');const blob=await response.blob();if(blob.type==='image/png')return blob;const bitmap=await createImageBitmap(blob),canvas=document.createElement('canvas');canvas.width=bitmap.width;canvas.height=bitmap.height;canvas.getContext('2d').drawImage(bitmap,0,0);bitmap.close();return new Promise((resolve,reject)=>canvas.toBlob(b=>b?resolve(b):reject(new Error('Copia immagine non riuscita.')),'image/png'));})();
|
||||
await navigator.clipboard.write([new ClipboardItem({'image/png':png})]);
|
||||
}
|
||||
|
||||
function videoComparison(stage,first,second,bridge,dialog,hint){
|
||||
stage.classList.add('dap-video-compare');const media=[];
|
||||
for(const [i,item] of [first,second].entries()){
|
||||
const panel=document.createElement('div');panel.className='dap-video-panel';const label=document.createElement('span');label.textContent=i?'B':'A';const element=document.createElement(item.job.kind==='video'?'video':'img');element.src=bridge.view(item.file);if(element.tagName==='VIDEO'){element.muted=i>0;element.playsInline=true;element.preload='metadata';}panel.append(element,label);stage.append(panel);media.push(element);
|
||||
}
|
||||
const videos=media.filter(e=>e.tagName==='VIDEO'),controls=document.createElement('div');let master=videos[0];controls.className='dap-video-sync';
|
||||
const play=document.createElement('button');play.textContent='Play / Pausa';const seek=document.createElement('input');seek.type='range';seek.min='0';seek.max='0';seek.step='.01';seek.value='0';seek.setAttribute('aria-label','Posizione confronto video');const time=document.createElement('span');
|
||||
const pause=()=>videos.forEach(v=>v.pause());
|
||||
const sync=()=>{for(const v of videos)if(v!==master&&Number.isFinite(v.duration)&&Math.abs(v.currentTime-master.currentTime)>.12)v.currentTime=Math.min(master.currentTime,v.duration);};
|
||||
play.onclick=async()=>{if(!master.paused){pause();return;}if(master.ended)for(const v of videos)v.currentTime=0;sync();try{await Promise.all(videos.filter(v=>!v.ended||v.currentTime===0).map(v=>v.play()));}catch{pause();hint.textContent='Riproduzione non disponibile: controlla i file video.';}};
|
||||
seek.oninput=()=>{for(const v of videos)if(Number.isFinite(v.duration))v.currentTime=Math.min(Number(seek.value),v.duration);};
|
||||
const update=()=>{const max=Math.max(0,...videos.map(v=>Number.isFinite(v.duration)?v.duration:0));seek.max=String(max);seek.value=String(master.currentTime);time.textContent=`${master.currentTime.toFixed(1)}s / ${max.toFixed(1)}s`;sync();};
|
||||
for(const v of videos){v.addEventListener('loadedmetadata',()=>{master=videos.reduce((a,b)=>(b.duration||0)>(a.duration||0)?b:a);update();});v.addEventListener('timeupdate',()=>{if(v===master)update();});v.addEventListener('ended',()=>{if(v===master)pause();});}controls.append(play,seek,time);stage.after(controls);hint.textContent='A / B · Riproduzione e posizione sincronizzate';
|
||||
dialog.addEventListener('close',()=>{pause();for(const v of videos){v.removeAttribute('src');v.load();}},{once:true});
|
||||
}
|
||||
|
||||
export function hoverCompare(host,generated,original){
|
||||
const a=document.createElement('img');a.src=generated;a.alt='Generata';a.draggable=false;a.className='dap-generated';host.append(a);host.classList.add('dap-compare-host');
|
||||
let cover=null,line=null;
|
||||
if(original){
|
||||
cover=document.createElement('div');cover.className='dap-original-cover';const b=document.createElement('img');b.src=original;b.alt='Image 1 / originale';b.draggable=false;cover.append(b);
|
||||
line=document.createElement('div');line.className='dap-compare-line';host.append(cover,line);
|
||||
const move=e=>{const rect=host.getBoundingClientRect();const percent=Math.max(0,Math.min(100,(e.clientX-rect.left)/rect.width*100));cover.style.clipPath=`inset(0 ${100-percent}% 0 0)`;line.style.left=percent+'%';};
|
||||
host.addEventListener('pointerenter',()=>host.classList.add('comparing'));host.addEventListener('pointermove',move);host.addEventListener('pointerleave',()=>host.classList.remove('comparing'));
|
||||
}
|
||||
return {image:a,cover,line};
|
||||
}
|
||||
|
||||
export function openViewer(ui,item,other=null){
|
||||
const {job,file,index=0}=item,bridge=ui.bridge;
|
||||
const title=savedFilename(job,index)||job.label||'DOGMA';
|
||||
const dialog=ui.modalBox(title,'dap-viewer-modal',!!item.preview),toolbar=document.createElement('div');toolbar.className='dap-viewer-tools';
|
||||
const stage=document.createElement('div');stage.className='dap-viewer-stage';stage.setAttribute('aria-label','Immagine ingrandita: rotella per zoom, trascina per spostare');stage.tabIndex=0;
|
||||
const surface=document.createElement('div');surface.className='dap-viewer-surface';stage.append(surface);
|
||||
const button=(name,label,fn)=>{const b=document.createElement('button');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(icon(name));b.onclick=fn;return b;};
|
||||
let scale=1,fitScale=1,x=0,y=0,width=0,height=0,drag=null,pinch=null;const points=new Map();
|
||||
const zoom=document.createElement('input');zoom.type='number';zoom.min='1';zoom.max='1600';zoom.setAttribute('aria-label','Zoom percentuale');
|
||||
const percent=document.createElement('label');percent.className='dap-zoom-value';percent.append(zoom,document.createTextNode('%'));
|
||||
const update=()=>{surface.style.transform=`translate(${x}px,${y}px) scale(${scale})`;zoom.value=String(Math.round(scale*100));stage.classList.toggle('zoomed',scale>fitScale*1.01);};
|
||||
const at=(next,cx=stage.clientWidth/2,cy=stage.clientHeight/2)=>{next=Math.max(Math.min(fitScale,.1)*.5,Math.min(16,next));const ratio=next/scale;x=cx-(cx-x)*ratio;y=cy-(cy-y)*ratio;scale=next;update();};
|
||||
const fit=()=>{if(!width)return;fitScale=Math.min((stage.clientWidth-30)/width,(stage.clientHeight-30)/height);scale=fitScale;x=(stage.clientWidth-width*scale)/2;y=(stage.clientHeight-height*scale)/2;update();};
|
||||
toolbar.append(button('zoomOut','Riduci zoom',()=>at(scale/1.3)),percent,button('zoomIn','Aumenta zoom',()=>at(scale*1.3)),button('fit','Adatta alla finestra',fit));
|
||||
const one=button('single','Dimensione reale 100%',()=>at(1));one.append(document.createTextNode('100%'));toolbar.append(one);
|
||||
if(job.id){const folder=button('folder','Mostra nella cartella',()=>ui.openOutput(job,index));folder.append(document.createTextNode('Mostra nella cartella'));toolbar.append(folder);}
|
||||
const download=button('download','Scarica file',()=>ui.downloadImage(file));toolbar.append(download);
|
||||
const hint=document.createElement('p');hint.className='dap-viewer-hint';hint.textContent='Rotella: zoom sul punto · Trascina: sposta · Doppio clic: 100% · Esc o clic nel vuoto: chiudi';
|
||||
dialog.append(toolbar,stage,hint);
|
||||
if(job.prompt)toolbar.append(button('prompt','Leggi e copia prompt',()=>ui.showPrompt(job)));
|
||||
if(job.kind!=='video'){const copy=button('copy','Copia immagine a piena risoluzione',async()=>{try{await copyFullImage(bridge.view(file));hint.textContent='Immagine copiata alla risoluzione originale.';}catch(e){hint.textContent=e.message;}});toolbar.append(copy);}
|
||||
if(other&&(job.kind==='video'||other.job.kind==='video')){surface.remove();toolbar.querySelectorAll('button').forEach(b=>{if(b.title.includes('zoom')||b.title.includes('100%')||b.title.includes('Adatta'))b.remove();});percent.remove();videoComparison(stage,item,other,bridge,dialog,hint);return;}
|
||||
if(job.kind==='video'){
|
||||
const video=document.createElement('video');video.src=bridge.view(file);video.controls=true;video.autoplay=true;video.className='dap-viewer-video';stage.append(video);surface.remove();toolbar.querySelectorAll('button').forEach(b=>{if(b.title.includes('zoom')||b.title.includes('100%')||b.title.includes('Adatta'))b.remove();});percent.remove();hint.textContent='Esc o clic nel vuoto per chiudere';
|
||||
dialog.addEventListener('close',()=>{video.pause();video.removeAttribute('src');video.load();},{once:true});return;
|
||||
}
|
||||
const original=other?bridge.view(other.file):job.imageEdit&&job.baseReference?(job.baseReference.comparePreview||bridge.view(job.baseReference.processedPreview||job.baseReference.file)):null;
|
||||
const compare=hoverCompare(surface,bridge.view(file),original);
|
||||
compare.image.onload=()=>{width=compare.image.naturalWidth;height=compare.image.naturalHeight;surface.style.width=width+'px';surface.style.height=height+'px';fit();};
|
||||
if(compare.image.complete&&compare.image.naturalWidth)compare.image.onload();
|
||||
compare.image.onerror=()=>{hint.textContent='File non disponibile. Potrebbe essere stato spostato.';};
|
||||
zoom.onchange=()=>{const value=Number(zoom.value);if(Number.isFinite(value)&&value>0)at(value/100);};
|
||||
stage.addEventListener('wheel',e=>{e.preventDefault();const r=stage.getBoundingClientRect();at(scale*Math.exp(-e.deltaY*.0017),e.clientX-r.left,e.clientY-r.top);},{passive:false});
|
||||
stage.addEventListener('dblclick',e=>{const r=stage.getBoundingClientRect();if(Math.abs(scale-1)<.02)fit();else at(1,e.clientX-r.left,e.clientY-r.top);});
|
||||
stage.addEventListener('pointerdown',e=>{
|
||||
const rect=surface.getBoundingClientRect();const inImage=e.clientX>=rect.left&&e.clientX<=rect.right&&e.clientY>=rect.top&&e.clientY<=rect.bottom;
|
||||
if(!inImage&&e.target===stage){drag={blank:true,startX:e.clientX,startY:e.clientY};return;}
|
||||
stage.setPointerCapture(e.pointerId);points.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={startX:e.clientX,startY:e.clientY,x,y};
|
||||
if(points.size===2){const [a,b]=[...points.values()];pinch={distance:Math.hypot(a.x-b.x,a.y-b.y),scale};}
|
||||
});
|
||||
stage.addEventListener('pointermove',e=>{
|
||||
if(points.has(e.pointerId))points.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
||||
if(points.size===2&&pinch){const [a,b]=[...points.values()],r=stage.getBoundingClientRect();at(pinch.scale*Math.hypot(a.x-b.x,a.y-b.y)/pinch.distance,(a.x+b.x)/2-r.left,(a.y+b.y)/2-r.top);return;}
|
||||
if(drag&&!drag.blank&&points.size===1){x=drag.x+e.clientX-drag.startX;y=drag.y+e.clientY-drag.startY;update();}
|
||||
});
|
||||
const up=e=>{if(drag?.blank&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<5)dialog.close();points.delete(e.pointerId);drag=null;pinch=null;};
|
||||
stage.addEventListener('pointerup',up);stage.addEventListener('pointercancel',up);
|
||||
stage.addEventListener('keydown',e=>{if(e.key==='+'||e.key==='='){e.preventDefault();at(scale*1.3);}if(e.key==='-'){e.preventDefault();at(scale/1.3);}if(e.key==='0'){e.preventDefault();fit();}});
|
||||
const observer=new ResizeObserver(()=>{if(Math.abs(scale-fitScale)<.01)fit();});observer.observe(stage);dialog.addEventListener('close',()=>observer.disconnect(),{once:true});
|
||||
}
|
||||
Reference in New Issue
Block a user