Compare commits

..
5 Commits
16 changed files with 396 additions and 39 deletions
+3
View File
@@ -0,0 +1,3 @@
# DOGMA 1.0.58
Add `DOGMASeedanceVideoFix`, a standalone native VIDEO adapter for the existing 1.0.57 stutter repair. It takes only the generated video and returns the corrected video, with progress, cancellation and a clear result status. No API jobs or original-footage input. Native LoadVideo and SaveVideo complete the three-node workflow. Keep SaveVideo codec auto to avoid a second re-encode. Existing nodes and the API Platform repair engine are unchanged; no new dependencies.
+5
View File
@@ -0,0 +1,5 @@
# DOGMA 1.0.59
Fix **Correggi scatti** rejecting valid videos whose duration is not an exact number of milliseconds. Preserve source-clock precision in both MP4 movie and video track headers instead of using the default 1000 Hz movie clock. Applies to the shared NVIDIA and software repair encoder. Strict duration, frame timestamp, fps, color and audio checks are unchanged; no tolerance is loosened and no extra processing pass is added.
Validation: real API output-node execution, corrected-copy export and UI record; 457-frame 24 fps failure case; 24/25/60 and 24000/1001, 30000/1001, 60000/1001 timing cases through both encoders; fractional-fps audio preserved; a deliberate one-frame duration mismatch still rejected; repair disabled, error retention, cancellation and concurrent output naming. No paid generation requests were made. Existing API Platform and standalone workflows remain compatible.
+8
View File
@@ -0,0 +1,8 @@
# DOGMA 1.0.60
- Add synchronized, persistent Compare ON/OFF switches in gallery filters and the enlarged-image toolbar, using the existing compact lever style.
- Disable image hover comparison immediately when OFF, including an already visible overlay. Explicit A/B selection continues to open and enable comparison automatically. Show the enlarged-image control as unavailable when no comparison image exists.
- Remove only the excess left inset below Image/Video. Preserve the right edge, with references, prompt, workspace and models aligned in both modes.
- Refresh frontend module/style cache versions. No changes to API execution, video repair, dependencies or workflow identifiers.
Verified in the local browser preview with the real UI modules: switch synchronization, OFF persistence after reload, keyboard interaction, overlay ON/OFF, zoom, automatic A/B, missing-reference state, and exact section/tab edge alignment in Image and Video. Package integrity checked without publication or paid generation.
+9
View File
@@ -0,0 +1,9 @@
# DOGMA 1.0.61
- Reorder model blocks by dragging their existing headings vertically, with no additional controls.
- Save model order in the session/workflow and retain it across reloads and Image/Video mode changes. Ignore unknown or duplicated saved keys and include newly available models.
- Preserve expansion, switches and all parameter values while moving existing blocks. Keep ordinary heading clicks and cancel a drag released outside the list. Support Escape and edge scrolling.
- Align the visible sidebar switches with the Image/Video tabs and section dividers while retaining their click-target sizes and the existing text positions.
- Change presentation only: generation planning, seeds, API payloads, video repair and workflow identifiers are unchanged.
Verified with the actual UI in the local browser preview: upward and downward drag, outside-drop cancellation, persistence after reload and mode switching, normal accordion clicks and enable switches. Sidebar switch, divider and tab edges match in Image and Video mode. Generation plans and compiled payloads checked before/after visual reordering. JavaScript syntax and package integrity checked without publication or paid generation.
+9
View File
@@ -0,0 +1,9 @@
# DOGMA 1.0.62
- Fix false Seedream rejection of odd Custom dimensions. Preserve the exact requested width and height, including 2816 × 1485.
- Respect preset precedence over unused Custom fields. Check Seedream's actual megapixel/range/aspect limits before queueing and identify the relevant fields.
- Reveal invalid fields and clear their validation error after correction. Release submission state and queue hooks even when preparation or native submission fails; allow a manual retry without restart.
- Replace a reference when files are dropped onto its thumbnail. Preserve slot/state/role and clear obsolete masks/crops/previews. Keep the original reference if upload fails; validate image/video and First/Last constraints before upload.
- No changes to workflow IDs, API authentication, backend generation or video repair. No paid requests or automatic retries during verification.
Validation: exact Custom payload and preset regression tests; real Seedream limits; upload failures and replacement routing with hidden references; image/video and First/Last roles; Run and queue failure/retry cleanup. Browser preview confirmed invalid-field focus, correction to 2816 × 1485, and successful mocked resubmission after a simulated Comfy error. Package integrity and JavaScript syntax checked.
+43
View File
@@ -213,3 +213,46 @@ Enable **Correggi scatti** in Video to save both the original and `_FIX.mp4`. Bo
The detector operates on small previews; RIFE reconstructs only selected frames at source resolution. Reliable pans with repeated jumps may additionally receive small camera translations, capped at 0.4% of width/height. This extends a thin edge strip by reflection instead of cropping or zooming. Camera refinement and interpolation share one encoding pass. Clean clips, poorly tracked shots, zooms and reversing camera paths are not stabilized. Frame count, timestamps, source bit depth and audio packet identity are checked before accepting the second file. A motion-based quality gate is an additional check, not a guarantee against every possible visual artifact. The method is independent of source fps and has no fixed clip-duration setting; processing time and memory grow with frame count and resolution. It does not impose 24 fps. CUDA and NVIDIA video encoding provide the fast path; CPU/software fallback is slower. First use includes model download and GPU initialization. No video is uploaded to another service. Generative deformations or newly invented content cannot be reliably restored by a cadence repair.
RIFE 4.26 code/weights: https://github.com/hzwer/Practical-RIFE (MIT; LICENSE_RIFE.txt). Verified weights are automatically cached under `models/DOGMA/rife`. Architecture derived from the official model archive, revision `01fdc7e97404120c243c3ea7b427046e5dc7643e`. DOGMA motion detection, timestamp planning and integration are separate from RIFE inference. No other ComfyUI interpolation extension is required.
## Standalone Seedance fix / 1.0.58
`Load Video → DOGMA / Fix video Seedance → Save Video` uses only the generated video. No original footage, API generation, credentials or credits are needed. The node reuses the unchanged 1.0.57 repair engine and its cached RIFE weights. Progress and a short result message are reported in ComfyUI. Clips without confidently detected stutter are returned unchanged; a rejected correction is explicitly reported as unchanged.
Use MP4 and codec **auto** in Save Video to preserve the corrected stream without another encoding pass. The supplied standalone workflow writes to `output/DOGMA/SeedanceFix/Seedance_FIX_*.mp4`. Duration, fps, frame timestamps, dimensions, color depth and audio are checked by the repair engine. The uploaded source is not overwritten. The fix runs outside the async event loop; Stop cancels processing and removes that attempt's partial files. Intermediate output and diagnostics live in ComfyUI's temp directory, so cached results can be saved again without repeating inference.
Existing API Platform, H3 and HDR workflows remain compatible. The same package supports Windows and the pod. No extra node pack is required.
## Correggi scatti: precise MP4 timing / 1.0.59
Fix the shared repair encoder used by API Platform's **Correggi scatti** switch and the standalone Seedance fix node. MP4's default 1000 Hz movie clock could truncate fractional-second clip ends and trigger "La durata del file corretto è cambiata", even with every frame and timestamp intact. For example, a 457-frame, 24 fps clip was rejected because the reported duration differed by eight video-clock ticks.
Both the NVIDIA and software encoder now use the source video's time base for the MP4 movie and video track clocks. The strict checks on frame count, timestamps, duration, fps, dimensions, color depth and copied audio remain in place. This changes only the container timing; motion analysis, interpolation, quality gates and correction settings are unchanged. It adds no interpolation or encoding pass.
When enabled, API Platform saves the generated original and a second locally processed copy in the existing project/scene workspace. Turning the switch off skips repair. Stop and real processing errors retain the original and report the outcome; an unsuccessful correction is never presented as repaired. Existing workflows and node IDs are compatible, with no new dependencies and the same code on Windows and the pod.
## Compare controls and sidebar alignment / 1.0.60
API Platform now has a compact **Compare** switch next to **Mostra errori** in the gallery filters and at the right of the enlarged image toolbar. Both controls share one saved session preference. OFF removes the original/reference overlay and divider immediately; ON enables the existing pointer comparison. Existing sessions default to ON. Selecting an explicit A/B pair still opens the comparison automatically and enables Compare. The enlarged-image switch is unavailable when there is no second image to compare.
The extra left inset below the Image/Video tabs is removed from the controls and Image Edit row. References, prompt, filename/workspace and model sections now align with the left edge of the tabs; their existing right edge is preserved. Works in Image and Video mode. Existing node IDs, generation behavior, video repair and workflow JSON are unchanged.
## Drag to reorder models / 1.0.61
Drag an existing model heading up or down to change the order of the blocks under **MODELS**. The order is saved with the session/workflow, including when switching between Image and Video. No new buttons or drag handles are added. A normal click still expands or collapses the model; switches, quantities and parameters keep their usual behavior. Drag near the sidebar edge to scroll, or release outside the list / press Escape to cancel.
The visible switches in model headings, Image Edit, the date row and video repair align with the left edge of the Image/Video tabs and section dividers. Their existing click targets and text positions are preserved; switches inside reference thumbnails and parameter fields keep their own inset.
Generation quantities and seeds, API execution, video repair behavior and existing workflow identifiers remain unchanged. Previous workflows load with their original model order.
## Seedream Custom dimensions and reference replacement / 1.0.62
Seedream Custom dimensions such as **2816 × 1485** are submitted exactly as entered. The previous DOGMA check incorrectly treated the native widget's increment of 2 as a mandatory divisibility rule. Selecting a size preset now validates that preset, rather than the unused Custom values. Current Seedream pixel-count and aspect-ratio limits are checked before submission; errors identify and reveal the affected fields. Correcting a value allows Run to be retried without reopening Comfy. Submission cleanup also restores the queue hooks and releases the DOGMA lock after preparation or queue failures. No automatic retries or dimension rounding are introduced.
Drop an image or video file directly on an existing reference thumbnail to replace that slot. Drops elsewhere keep adding references. If multiple files are dropped onto a thumbnail, the first replaces it and the remaining files are added. Replacement preserves position, enabled state, modes and First/Last role; old masks, crops and previews are discarded because they belong to the previous file. A failed upload leaves the old reference intact. Image-only modes still reject video, and First/Last mode still permits at most two images.
Existing workflow JSON, model ordering, compare controls and video-repair behavior remain unchanged.
+12
View File
@@ -243,3 +243,15 @@ try:
del _APIV2, _APIV2_NAMES, _APIV2_ROUTES
except Exception as _apiv2_error:
print("[DOGMA API V2] Unavailable; previous DOGMA nodes preserved:", _apiv2_error)
# Standalone Seedance fix: same engine as API Platform, one VIDEO input.
try:
from .dogma_video_fix_node import NODE_CLASS_MAPPINGS as _FIX158, NODE_DISPLAY_NAME_MAPPINGS as _FIX158_NAMES
if set(_FIX158).intersection(NODE_CLASS_MAPPINGS):
raise RuntimeError("DOGMA Seedance fix: node ID collision")
NODE_CLASS_MAPPINGS.update(_FIX158)
NODE_DISPLAY_NAME_MAPPINGS.update(_FIX158_NAMES)
del _FIX158, _FIX158_NAMES
except Exception as _fix158_error:
print("[DOGMA Seedance fix] Unavailable; previous DOGMA nodes preserved:", _fix158_error)
+81
View File
@@ -0,0 +1,81 @@
"""Standalone VIDEO adapter for the same repair engine used by API Platform."""
import asyncio
import json
from pathlib import Path
import tempfile
import threading
from comfy_api.latest import io, ui, InputImpl, Types
class DOGMASeedanceVideoFix(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="DOGMASeedanceVideoFix",
display_name="DOGMA / Fix video Seedance",
category="DOGMA/Video",
description="Corregge gli scatti del solo video generato da Seedance. "
"Mantiene fps, durata, risoluzione e audio. Non richiede il video originale o API.",
inputs=[io.Video.Input("video", tooltip="Collega il video generato da Seedance.")],
outputs=[io.Video.Output("video_corretto")],
hidden=[io.Hidden.unique_id],
)
@classmethod
async def execute(cls, video):
cancelled=threading.Event()
worker=asyncio.create_task(asyncio.to_thread(cls._repair,video,cancelled,cls.hidden.unique_id))
try:
result,summary=await asyncio.shield(worker)
return io.NodeOutput(result,ui=ui.PreviewText(summary))
except asyncio.CancelledError:
cancelled.set()
try:await worker
except Exception:pass
raise
@staticmethod
def _repair(video,cancelled,node_id=None):
import folder_paths
import comfy.model_management as management
from comfy.utils import ProgressBar
from .dogma_video_repair import RepairCancelled,repair_video
progress=ProgressBar(100,node_id=node_id)
def check():
if cancelled.is_set():raise RepairCancelled("Correzione interrotta.")
management.throw_exception_if_processing_interrupted()
def update(stage,fraction):
check()
progress.update_absolute(round(max(0,min(1,fraction))*100))
check()
root=Path(folder_paths.get_temp_directory());root.mkdir(parents=True,exist_ok=True)
work=Path(tempfile.mkdtemp(prefix="dogma-seedance-fix-",dir=root))
source=work/'input.mp4';fixed=work/'corrected.mp4';report_file=work/'repair.json'
try:
# Native save remuxes uploaded MP4 streams. It also honors VIDEO trims
# if this node is reused in a larger graph, without tensorizing the clip.
video.save_to(str(source),format=Types.VideoContainer.MP4,codec=Types.VideoCodec.AUTO)
check()
report=repair_video(source,fixed,Path(folder_paths.models_dir)/'DOGMA'/'rife',cancel=check,progress=update)
check()
if report['status']=='repaired':
summary=f"Correzione completata · {report['fps']} fps · {report['interpolated_frames']} fotogrammi ricostruiti"
elif report['status']=='unchanged':
summary="Nessuno scatto riconosciuto: il video è rimasto invariato."
else:
summary="Correzione non applicata: il controllo non ha confermato un miglioramento. Video invariato."
report_file.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf8')
source.unlink()
# The result stays in Comfy's temp directory for SaveVideo and caching.
return InputImpl.VideoFromFile(str(fixed)),summary
except BaseException:
for path in (source,fixed,report_file):path.unlink(missing_ok=True)
work.rmdir()
raise
NODE_CLASS_MAPPINGS={"DOGMASeedanceVideoFix":DOGMASeedanceVideoFix}
NODE_DISPLAY_NAME_MAPPINGS={"DOGMASeedanceVideoFix":"DOGMA / Fix video Seedance"}
+6 -1
View File
@@ -359,7 +359,12 @@ def _encoder(path, meta):
for codec,pixel,options in candidates:
container = None
try:
container = av.open(str(path),'w',format='mp4',options={'movflags':'+faststart'})
# MP4's default 1000 Hz movie clock truncates fractional-frame ends
# in edit lists (e.g. 457/24 s became 19.041015625 s). Use the source
# clock for both the movie and video track; keep strict verification.
clock=str(Fraction(meta['time_base']).denominator)
container = av.open(str(path),'w',format='mp4',options={
'movflags':'+faststart','movie_timescale':clock,'video_track_timescale':clock})
stream = container.add_stream(codec,rate=Fraction(meta['fps']))
stream.width=meta['width'];stream.height=meta['height'];stream.pix_fmt=pixel;stream.options=options
stream.time_base=Fraction(meta['time_base']);stream.codec_context.time_base=stream.time_base
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-dogma-nodes"
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
version = "1.0.57"
version = "1.0.62"
license = { file = "LICENSE" }
dependencies = ["scipy>=1.10", "av>=18.0", "opencv-python>=4.8"]
+39 -8
View File
@@ -8,6 +8,10 @@ export const FAMILIES=[
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 function orderedFamilies(s){
const available=families(s),order=Array.isArray(s.modelOrder)?s.modelOrder:[];
return [...new Set([...order,...available.map(f=>f.key)])].map(key=>available.find(f=>f.key===key)).filter(Boolean);
}
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;
@@ -47,7 +51,8 @@ export function migrateState(raw){
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;s.videoRepair ??= false;
s.filters.hideErrors ??= false;s.videoRepair ??= false;s.compareEnabled ??= true;
s.modelOrder=[...new Set([...(Array.isArray(s.modelOrder)?s.modelOrder:[]),...ALL_FAMILIES.map(f=>f.key)])].filter(key=>ALL_FAMILIES.some(f=>f.key===key));
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';
@@ -57,7 +62,36 @@ export function plannedJobs(s){const repeats=Number(s.runCount??1);if(!Number.is
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){
export function mediaKind(file){
if(file.type?.startsWith('image/'))return 'image';if(file.type?.startsWith('video/'))return 'video';
if(file.type&&file.type!=='application/octet-stream')return null;
if(/\.(png|jpe?g|webp|avif|gif|bmp|tiff?)$/i.test(file.name||''))return 'image';
if(/\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(file.name||''))return 'video';return null;
}
function dimensionError(f,fields,message){return Object.assign(new Error(`${f.name}: ${message}`),{family:f.key,fields});}
function validateDimensions(f,p,specFor){
const seedream=f.key==='seedream',model=String(p.model||'').toLowerCase();
const modern=seedream&&(/5[.-]5/.test(model)||/5[.-]0.*(?:pro|flash)/.test(model));
const preset=seedream&&p['model.size_preset']&&p['model.size_preset']!=='Custom';
if(!preset)for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
const info=specFor?.(f,k)?.[1]||{},n=Number(v);
const min=info.min??(seedream&&!/5[.-]5/.test(model)?1024:f.key==='gpt'?480:240);
const max=info.max??(seedream?(/5[.-]5/.test(model)?8594:modern?4514:k.endsWith('width')?6240:4992):f.key==='gpt'?3840:8594);
// Seedream's step=2 is a widget increment, not a server-side divisibility rule.
const step=seedream?1:f.key==='gpt'?16:2,label=k.split('.').at(-1).toUpperCase();
if(!Number.isInteger(n)||n<min||n>max||n%step)throw dimensionError(f,[k],`${label} = ${v}. Inserisci un intero da ${min} a ${max}${step>1?`, multiplo di ${step}`:''}.`);
}
if(!seedream)return;
const match=preset&&String(p['model.size_preset']).match(/(\d+)\s*[x×]\s*(\d+)/i);
// Presets retain native precedence over the unused Custom width and height.
const w=Number(match?match[1]:p['model.width']),h=Number(match?match[2]:p['model.height']);
if(preset&&!match)return;
const fields=preset?['model.size_preset']:['model.width','model.height'];
const pixels=w*h,min=modern||/4[.-]0/.test(model)?921600:3686400,max=modern?4624220:16777216;
if(pixels<min||pixels>max)throw dimensionError(f,fields,`${p.model}: ${w} × ${h} = ${(pixels/1e6).toFixed(2)} MP. Il modello richiede da ${(min/1e6).toFixed(2)} a ${(max/1e6).toFixed(2)} MP. Correggi ${preset?'SIZE PRESET':'WIDTH / HEIGHT'} e premi Run.`);
if(/5[.-]5/.test(model)&&(w/h<1/16||w/h>16))throw dimensionError(f,fields,`${w} × ${h}: rapporto consentito da 1:16 a 16:1. Correggi ${preset?'SIZE PRESET':'WIDTH / HEIGHT'} e premi Run.`);
}
export function validateState(s,specFor){
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');
@@ -77,14 +111,11 @@ export function validateState(s){
}
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}.`);
}
validateDimensions(f,p,specFor);
}
}
export function compileBatch(s,jobs,baseSeed){
validateState(s);const output={},refs=activeReferences(s),images=[],videos=[];
export function compileBatch(s,jobs,baseSeed,specFor){
validateState(s,specFor);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;}
+65
View File
@@ -0,0 +1,65 @@
// Reorder only the model blocks. Controls and expansion state stay on their DOM nodes.
export function modelReorder(container,saveOrder){
let active=null,frame=0,suppressClick=false,scroller=null;
const models=()=>[...container.children].filter(e=>e.dataset.modelKey);
const inside=()=>{
const r=container.getBoundingClientRect(),s=scroller.getBoundingClientRect();
return active.x>=r.left&&active.x<=r.right&&active.y>=Math.max(r.top,s.top)&&active.y<=Math.min(r.bottom,s.bottom);
};
const place=()=>{
if(!inside())return;
const next=models().find(row=>{
if(row===active.row)return false;
const r=row.querySelector('.dap-model-head>details>summary').getBoundingClientRect();
return active.y<r.top+r.height/2;
});
if(active.row.nextElementSibling!==next&&(next||active.row!==container.lastElementChild))container.insertBefore(active.row,next||null);
};
const scroll=()=>{
if(!active?.dragging)return;
if(!container.isConnected){finish(false);return;}
const r=scroller.getBoundingClientRect();
if(active.x>=r.left&&active.x<=r.right){
const delta=active.y<r.top+36?-Math.min(12,(r.top+36-active.y)/3):active.y>r.bottom-36?Math.min(12,(active.y-r.bottom+36)/3):0;
if(delta){scroller.scrollTop+=delta;place();}
}
frame=requestAnimationFrame(scroll);
};
const finish=(commit=false)=>{
if(!active)return;
const {row,original,dragging,pointerId}=active;
active=null;cancelAnimationFrame(frame);row.classList.remove('dap-model-dragging');
document.removeEventListener('pointermove',move);document.removeEventListener('pointerup',up);document.removeEventListener('pointercancel',cancel);
document.removeEventListener('keydown',key,true);window.removeEventListener('blur',cancel);
if(container.hasPointerCapture(pointerId))container.releasePointerCapture(pointerId);
if(!dragging)return;
suppressClick=true;setTimeout(()=>suppressClick=false,0);
if(!commit){for(const item of original)container.append(item);return;}
const order=models().map(item=>item.dataset.modelKey);
if(order.some((value,i)=>value!==original[i].dataset.modelKey))saveOrder(order);
};
const move=e=>{
if(!active||e.pointerId!==active.pointerId)return;
active.x=e.clientX;active.y=e.clientY;
if(!active.dragging){
if(Math.hypot(e.clientX-active.startX,e.clientY-active.startY)<6)return;
active.dragging=true;container.setPointerCapture(e.pointerId);active.row.classList.add('dap-model-dragging');frame=requestAnimationFrame(scroll);
}
e.preventDefault();place();
};
const up=e=>{if(active&&e.pointerId===active.pointerId){active.x=e.clientX;active.y=e.clientY;if(active.dragging)e.preventDefault();finish(inside());}};
const cancel=()=>finish(false);
const key=e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();cancel();}};
container.addEventListener('pointerdown',e=>{
if(e.button!==0||e.pointerType==='touch'||active)return;
const summary=e.target.closest('.dap-model-head>details>summary');
if(!summary||!container.contains(summary))return;
scroller=container.closest('.dap-side');if(!scroller)return;
active={row:summary.closest('.dap-model'),original:models(),pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,x:e.clientX,y:e.clientY,dragging:false};
document.addEventListener('pointermove',move,{passive:false});document.addEventListener('pointerup',up);document.addEventListener('pointercancel',cancel);
document.addEventListener('keydown',key,true);window.addEventListener('blur',cancel);
});
container.addEventListener('click',e=>{if(suppressClick){e.preventDefault();e.stopPropagation();}},true);
container.addEventListener('dragstart',e=>{if(active)e.preventDefault();});
container.classList.add('dap-models-sortable');
}
+16
View File
@@ -187,3 +187,19 @@
.dap-video-repair{display:flex;align-items:center;flex-wrap:wrap;gap:4px;margin:-12px 0 24px;color:#aaa;font:13px Arial,sans-serif;cursor:pointer}
.dap-video-repair small{flex-basis:100%;margin-left:42px;color:#666;font:10px/1.6 Arial,sans-serif}
.dap-video-variant{position:absolute;top:12px;left:12px;padding:4px 7px;border-radius:4px;background:#000a;color:#ccc;font:10px Arial,sans-serif;pointer-events:none}
/* Match the left edge of Image/Video; keep the existing right edge. */
.dap-controls{padding-left:0}
.dap-edit-mode{padding-left:0}
/* Align the visible sidebar levers with the tabs and section dividers. */
.dap-edit-mode>.dap-toggle,.dap-date-row>.dap-toggle,.dap-model-head>.dap-toggle,.dap-video-repair>.dap-toggle{justify-content:flex-start}
.dap-viewer-tools>.dap-compare-toggle{margin-left:auto;font:11px Arial,Helvetica,sans-serif}
.dap-compare-toggle:has(input:disabled){cursor:default;color:#666}
/* The existing model heading is the drag target; no extra handle or toolbar. */
.dap-models-sortable>.dap-model>.dap-model-head>details>summary{cursor:grab;user-select:none}
.dap-models-sortable>.dap-model>.dap-model-head>details>summary:active{cursor:grabbing}
.dap-model-dragging{opacity:.55}
/* Explain validation in the affected field without adding permanent controls. */
.dap-field:has([aria-invalid="true"]){outline:1px solid var(--orange);outline-offset:-1px}
+12 -9
View File
@@ -1,9 +1,9 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.57';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.57';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.62';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.62';
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.57',ROOT);document.head.append(css);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.62',ROOT);document.head.append(css);
let opened=null,queueLock=false;
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.57',ROOT)).then(r=>r.json()).catch(()=>({}));
@@ -70,13 +70,16 @@ class ComfyBridge {
}
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)};
queueLock=true;let result=null,used=false,queueError=null,build,capture;
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;}
try{
const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
capture=async function(...args){try{const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;}catch(e){if(args[1]?.workflow===workflow)queueError=e;throw e;}};
app.graphToPrompt=build;api.queuePrompt=capture;
await app.queuePrompt(0,1);if(queueError)throw queueError;
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(build&&app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(capture&&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','dogma_video_repair'])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();}
+81 -15
View File
@@ -1,6 +1,7 @@
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.57';
import {ALL_FAMILIES,copy,families,orderedFamilies,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask,mediaKind} from './dogma_api_core.js?v=1.0.62';
import {icon} from './dogma_api_icons.js?v=1.0.57';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.57';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.60';
import {modelReorder} from './dogma_api_model_order.js?v=1.0.61';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.57';
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
@@ -17,7 +18,7 @@ export class PlatformUI {
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]);});
this.root.addEventListener('drop',e=>this.dropReferences(e));
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…');
@@ -86,7 +87,8 @@ export class PlatformUI {
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));
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of orderedFamilies(s))models.append(this.model(f));
if(models.querySelectorAll('.dap-model').length>1)modelReorder(models,order=>{s.modelOrder=[...order,...(s.modelOrder||[]).filter(key=>!order.includes(key))];this.save();});
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);}
if(s.mode==='video'){const fix=el('label','','dap-video-repair');fix.append(this.toggle('Correggi scatti',s.videoRepair,v=>{s.videoRepair=v;this.save();},'span'),el('span','Correggi scatti'));fix.append(el('small','Salva anche una seconda copia · durata e fps originali'));c.append(fix);}
c.append(refs,prompt,workLabel,workSection,models);
@@ -115,10 +117,42 @@ export class PlatformUI {
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);}}
dropReferences(e){
const files=[...(e.dataTransfer?.files||[])];if(!files.length)return;
e.preventDefault();e.stopPropagation();
const tile=e.target.closest?.('.dap-ref'),replace=tile&&this.refs?.contains(tile)?visibleReferences(this.state)[Number(tile.dataset.ref)]:null;
return this.addReferences(files,replace);
}
async addReferences(files,replace=null){
if(!files.length)return;
try{
const mode=this.state.mode,engine=this.state.models.seedance?.engine,frames=mode==='video'&&engine==='frames';
const kinds=files.map(mediaKind);
if(kinds.some(k=>!k))throw new Error('Scegli immagini o video.');
if(kinds.includes('video')&&(mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');
if(replace&&!this.state.references.includes(replace))throw new Error('La reference da sostituire non è più presente.');
if(frames&&visibleReferences(this.state).length+files.length-(replace?1:0)>2)throw new Error('First / Last frame accetta due immagini.');
this.note(replace?'Sostituzione reference…':'Caricamento reference…');
const uploaded=[];for(const file of files)uploaded.push(await this.bridge.upload(file));
if(this.closed)return;
if(this.state.mode!==mode||this.state.models.seedance?.engine!==engine)throw new Error('Modalità cambiata durante il caricamento. Rilascia nuovamente i file.');
const at=replace?this.state.references.indexOf(replace):-1;
if(replace&&at<0)throw new Error('La reference da sostituire è stata rimossa. Rilascia nuovamente il file.');
if(frames&&visibleReferences(this.state).length+files.length-(replace?1:0)>2)throw new Error('First / Last frame accetta due immagini.');
const roles=new Set(visibleReferences(this.state).filter(r=>r!==replace).map(r=>r.role));
const incoming=uploaded.map((item,i)=>{
const previous=i===0?replace:null,role=previous?.role||(frames?(!roles.has('first')?'first':'last'):'reference');roles.add(role);
return {...item,kind:kinds[i],enabled:previous?.enabled??true,modes:previous?.modes?[...previous.modes]:[mode],role,
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){this.state.references.splice(at,1,incoming[0]);this.state.references.push(...incoming.slice(1));}
else this.state.references.push(...incoming);
this.save();this.renderRefs();this.refreshPrices();this.note(replace?'Reference sostituita.':'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 m=this.state.models[f.key],wrap=el('div','','dap-model'),row=el('div','','dap-model-head');wrap.dataset.modelKey=f.key;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);
@@ -137,7 +171,7 @@ export class PlatformUI {
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);
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();this.recheckValidation();},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'));
@@ -156,7 +190,7 @@ export class PlatformUI {
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()));
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,this.compareToggle(),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);
@@ -172,7 +206,7 @@ export class PlatformUI {
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('playCircle'),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;}
}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,()=>this.state.compareEnabled!==false);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;
@@ -216,7 +250,18 @@ export class PlatformUI {
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]);}
compareToggle(available=true){
const label=el('label','','dap-error-filter dap-compare-toggle'),control=this.toggle('Compare',available&&this.state.compareEnabled!==false,v=>this.setCompareEnabled(v),'span');
const input=control.querySelector('input');input.dataset.compareToggle='';input.disabled=!available;
label.title=available?'Attiva o disattiva il confronto al passaggio del mouse':'Nessuna immagine di confronto disponibile';
label.append(control,el('span','Compare'));return label;
}
setCompareEnabled(enabled){
this.state.compareEnabled=!!enabled;this.save();
for(const input of this.root?.querySelectorAll('[data-compare-toggle]')||[])input.checked=!!enabled&&!input.disabled;
if(!enabled)for(const host of this.root?.querySelectorAll('.dap-compare-host.comparing')||[])host.classList.remove('comparing');
}
compare(){if(this.selection.length===2){this.setCompareEnabled(true);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);}}
@@ -254,11 +299,32 @@ export class PlatformUI {
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);}}
clearValidation(){
this.validationError=null;for(const input of this.controls?.querySelectorAll('[aria-invalid="true"]')||[])input.removeAttribute('aria-invalid');
}
reportValidation(error,focus=true){
this.clearValidation();this.validationError=error;this.note(error.message,true);
if(!error.family)return;
const model=[...(this.controls?.querySelectorAll('.dap-model')||[])].find(e=>e.dataset.modelKey===error.family);if(!model)return;
const fields=new Set((error.fields||[]).map(displayName)),inputs=[...model.querySelectorAll('input,select')].filter(e=>fields.has(e.getAttribute('aria-label')));
for(const input of inputs)input.setAttribute('aria-invalid','true');
if(focus){model.querySelector('details').open=true;this.state.models[error.family].expanded=true;this.save();
if(inputs[0]){inputs[0].focus({preventScroll:true});inputs[0].scrollIntoView({block:'center',inline:'nearest'});}
}
}
recheckValidation(){
if(!this.validationError)return;
try{validateState(this.state,(f,k)=>this.bridge.inputSpec?.(this.state,f,k));this.clearValidation();this.note('Parametri validi. Premi Run per generare.');}
catch(e){this.reportValidation(e,false);}
}
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:[]}));
if(this.busy||!this.ready)return;const specFor=(f,k)=>this.bridge.inputSpec?.(this.state,f,k);
try{validateState(this.state,specFor);}catch(e){this.reportValidation(e);return;}
this.clearValidation();let jobs=[];
try{
this.stopRequested=false;this.busy=true;this.pendingEvents=[];this.updateHeader();
const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
jobs=plannedJobs(snapshot).map((p,ordinal)=>({...p,id:crypto.randomUUID(),batch,started,batchStarted:started,ordinal,status:'submitting',images:[]}));
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)){
@@ -266,11 +332,11 @@ export class PlatformUI {
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);
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647,(f,k)=>this.bridge.inputSpec?.(snapshot,f,k));
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();}
}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.reportValidation(e);}finally{this.busy=false;this.pendingEvents=[];if(!this.closed)this.updateHeader();}
}
event(name,d){
if(name==='dogma_video_repair'){const job=this.state.results.find(j=>j.id===d?.job_id);if(job&&!terminal.has(job.status)){job.status='repairing';job.repairProgress=d.value;job.repairStage=d.stage;this.save();this.updateCards();}return;}
+6 -5
View File
@@ -1,5 +1,5 @@
import { icon } from './dogma_api_icons.js?v=1.0.57';
import {savedFilename} from './dogma_api_core.js?v=1.0.57';
import {savedFilename} from './dogma_api_core.js?v=1.0.60';
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.');
@@ -23,14 +23,14 @@ function videoComparison(stage,first,second,bridge,dialog,hint){
dialog.addEventListener('close',()=>{pause();for(const v of videos){v.removeAttribute('src');v.load();}},{once:true});
}
export function hoverCompare(host,generated,original){
export function hoverCompare(host,generated,original,enabled=()=>true){
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'));
const move=e=>{const active=enabled();host.classList.toggle('comparing',active);if(!active)return;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',move);host.addEventListener('pointermove',move);host.addEventListener('pointerleave',()=>host.classList.remove('comparing'));
}
return {image:a,cover,line};
}
@@ -62,7 +62,8 @@ export function openViewer(ui,item,other=null){
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);
toolbar.append(ui.compareToggle(!!original));
const compare=hoverCompare(surface,bridge.view(file),original,()=>ui.state.compareEnabled!==false);
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.';};