15 Commits

Author SHA1 Message Date
space-nuko
ce6f3b1273 Improve error list 2023-05-28 20:39:21 -05:00
space-nuko
fe736232a9 Enum support 2023-05-28 20:06:08 -05:00
space-nuko
e411d29f09 Basic settings screen 2023-05-28 18:41:54 -05:00
space-nuko
4d8390115d Config state temp2 2023-05-28 16:48:33 -05:00
space-nuko
8fc4b74aed Config state temp 2023-05-28 15:08:33 -05:00
space-nuko
0bc9d06910 Jump to node from widget properties button 2023-05-28 11:49:00 -05:00
space-nuko
3be662c598 Click toast item pointer change 2023-05-28 09:19:44 -05:00
space-nuko
0dce8bc2b3 Merge pull request #83 from space-nuko/mask-canvas
Mask canvas
2023-05-28 00:57:16 -05:00
space-nuko
45f7a8d2c1 Fix title 2023-05-28 00:47:51 -05:00
space-nuko
60d0fb3128 Update img2img masked workflow 2023-05-28 00:47:51 -05:00
space-nuko
9a29e124e9 Better combo menu width handling 2023-05-28 00:47:51 -05:00
space-nuko
c255e5b425 Show title for cut off select item entries 2023-05-28 00:47:51 -05:00
space-nuko
3b9d4533f9 Preserve mask when sending output into image upload 2023-05-28 00:47:48 -05:00
space-nuko
cb9e8540a0 Mask canvas for masked img2img 2023-05-28 00:47:27 -05:00
space-nuko
7e2b6111dd Merge pull request #79 from space-nuko/error-handling
Better error display
2023-05-28 00:46:47 -05:00
34 changed files with 17817 additions and 2323 deletions

View File

@@ -14,7 +14,7 @@
"lint": "prettier --plugin-search-dir . --check . && eslint .", "lint": "prettier --plugin-search-dir . --check . && eslint .",
"format": "prettier --plugin-search-dir . --write .", "format": "prettier --plugin-search-dir . --write .",
"svelte-check": "svelte-check", "svelte-check": "svelte-check",
"prebuild": "pnpm run build:css && pnpm --filter=klecks lang:build", "prebuild": "pnpm run build:css",
"build:css": "pollen -c gradio/js/theme/src/pollen.config.cjs && mv src/pollen.css node_modules/@gradio/theme/src" "build:css": "pollen -c gradio/js/theme/src/pollen.config.cjs && mv src/pollen.css node_modules/@gradio/theme/src"
}, },
"devDependencies": { "devDependencies": {
@@ -85,7 +85,6 @@
"framework7": "^8.0.3", "framework7": "^8.0.3",
"framework7-svelte": "^8.0.3", "framework7-svelte": "^8.0.3",
"img-comparison-slider": "^8.0.0", "img-comparison-slider": "^8.0.0",
"klecks": "workspace:*",
"pollen-css": "^4.6.2", "pollen-css": "^4.6.2",
"radix-icons-svelte": "^1.2.1", "radix-icons-svelte": "^1.2.1",
"style-mod": "^4.0.3", "style-mod": "^4.0.3",

1894
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,4 +2,3 @@ packages:
- 'gradio/js/*' - 'gradio/js/*'
- 'gradio/client/js' - 'gradio/client/js'
- 'litegraph/packages/*' - 'litegraph/packages/*'
- 'klecks'

View File

@@ -1,9 +0,0 @@
{
"comfyUIHostname": "localhost",
"comfyUIPort": 8188,
"alwaysStripUserState": false,
"promptForWorkflowName": false,
"confirmWhenUnloadingUnsavedChanges": false,
"builtInTemplates": ["ControlNet", "LoRA x5", "Model Loader", "Positive_Negative", "Seed Randomizer"],
"cacheBuiltInResources": true
}

File diff suppressed because it is too large Load Diff

View File

@@ -11,6 +11,7 @@ import queueState from "./stores/queueState";
import selectionState from "./stores/selectionState"; import selectionState from "./stores/selectionState";
import templateState from "./stores/templateState"; import templateState from "./stores/templateState";
import { calcNodesBoundingBox } from "./utils"; import { calcNodesBoundingBox } from "./utils";
import interfaceState from "./stores/interfaceState";
export type SerializedGraphCanvasState = { export type SerializedGraphCanvasState = {
offset: Vector2, offset: Vector2,
@@ -118,13 +119,7 @@ export default class ComfyGraphCanvas extends LGraphCanvas {
// color = "yellow"; // color = "yellow";
// thickness = 5; // thickness = 5;
// } // }
if (ss.currentHoveredNodes.has(node.id)) { if (nodeErrors) {
color = "lightblue";
}
else if (isRunningNode) {
color = "#0f0";
}
else if (nodeErrors) {
const hasExecutionError = nodeErrors.find(e => e.errorType === "execution"); const hasExecutionError = nodeErrors.find(e => e.errorType === "execution");
if (hasExecutionError) { if (hasExecutionError) {
blink = true; blink = true;
@@ -139,6 +134,12 @@ export default class ComfyGraphCanvas extends LGraphCanvas {
color = "cyan"; color = "cyan";
thickness = 2 thickness = 2
} }
else if (ss.currentHoveredNodes.has(node.id)) {
color = "lightblue";
}
else if (isRunningNode) {
color = "#0f0";
}
if (blink) { if (blink) {
if (nodeErrors && nodeErrors.includes(this.blinkError) && this.blinkErrorTime > 0) { if (nodeErrors && nodeErrors.includes(this.blinkError) && this.blinkErrorTime > 0) {
@@ -193,6 +194,8 @@ export default class ComfyGraphCanvas extends LGraphCanvas {
} }
} }
private static CONNECTION_POS: Vector2 = [0, 0];
private highlightNodeInput(node: LGraphNode, inputSlot: SlotNameOrIndex, ctx: CanvasRenderingContext2D) { private highlightNodeInput(node: LGraphNode, inputSlot: SlotNameOrIndex, ctx: CanvasRenderingContext2D) {
let inputIndex: number; let inputIndex: number;
if (typeof inputSlot === "number") if (typeof inputSlot === "number")
@@ -200,7 +203,7 @@ export default class ComfyGraphCanvas extends LGraphCanvas {
else else
inputIndex = node.findInputSlotIndexByName(inputSlot) inputIndex = node.findInputSlotIndexByName(inputSlot)
if (inputIndex !== -1) { if (inputIndex !== -1) {
let pos = node.getConnectionPos(true, inputIndex); let pos = node.getConnectionPos(true, inputIndex, ComfyGraphCanvas.CONNECTION_POS);
ctx.beginPath(); ctx.beginPath();
ctx.arc(pos[0] - node.pos[0], pos[1] - node.pos[1], 12, 0, 2 * Math.PI, false) ctx.arc(pos[0] - node.pos[0], pos[1] - node.pos[1], 12, 0, 2 * Math.PI, false)
ctx.stroke(); ctx.stroke();
@@ -700,6 +703,8 @@ export default class ComfyGraphCanvas extends LGraphCanvas {
} }
jumpToNode(node: LGraphNode) { jumpToNode(node: LGraphNode) {
interfaceState.update(s => { s.isJumpingToNode = true; return s; })
this.closeAllSubgraphs(); this.closeAllSubgraphs();
const subgraphs = Array.from(node.iterateParentSubgraphNodes()).reverse(); const subgraphs = Array.from(node.iterateParentSubgraphNodes()).reverse();
@@ -709,6 +714,7 @@ export default class ComfyGraphCanvas extends LGraphCanvas {
} }
this.centerOnNode(node); this.centerOnNode(node);
this.selectNode(node);
} }
jumpToNodeAndInput(node: LGraphNode, slotIndex: number) { jumpToNodeAndInput(node: LGraphNode, slotIndex: number) {

View File

@@ -12,6 +12,7 @@
import notify from "$lib/notify"; import notify from "$lib/notify";
import ComfyBoxWorkflowsView from "./ComfyBoxWorkflowsView.svelte"; import ComfyBoxWorkflowsView from "./ComfyBoxWorkflowsView.svelte";
import GlobalModal from "./GlobalModal.svelte"; import GlobalModal from "./GlobalModal.svelte";
import ComfySettingsView from "./ComfySettingsView.svelte";
export let app: ComfyApp = undefined; export let app: ComfyApp = undefined;
let hasShownUIHelpToast: boolean = false; let hasShownUIHelpToast: boolean = false;
@@ -63,6 +64,7 @@
<ComfyBoxWorkflowsView {app} {uiTheme} /> <ComfyBoxWorkflowsView {app} {uiTheme} />
</SidebarItem> </SidebarItem>
<SidebarItem id="settings" name="Settings" icon={Gear}> <SidebarItem id="settings" name="Settings" icon={Gear}>
<ComfySettingsView {app} />
</SidebarItem> </SidebarItem>
</Sidebar> </Sidebar>
</div> </div>

View File

@@ -261,18 +261,29 @@ export default class ComfyApp {
return Promise.resolve(); return Promise.resolve();
} }
/*
* TODO
*/
async loadConfig() { async loadConfig() {
try { try {
const config = await fetch(`/config.json`, { cache: "no-store" }); console.log("Loading config.json...")
const newConfig = await config.json() as ConfigState; const config = localStorage.getItem("config")
configState.set({ ...get(configState), ...newConfig }); if (config == null)
configState.loadDefault();
else
configState.load(JSON.parse(config));
} }
catch (error) { catch (error) {
console.error(`Failed to load config`, error) console.error(`Failed to load config, falling back to defaults`, error)
configState.loadDefault();
} }
// configState.onChange("linkDisplayType", (newValue) => {
// if (!this.lCanvas)
// return;
// this.lCanvas.links_render_mode = newValue;
// this.lCanvas.setDirty(true, true);
// })
configState.runOnChangedEvents();
} }
async loadBuiltInTemplates(): Promise<SerializedComfyBoxTemplate[]> { async loadBuiltInTemplates(): Promise<SerializedComfyBoxTemplate[]> {
@@ -997,6 +1008,7 @@ export default class ComfyApp {
if ("getPromptThumbnails" in node) { if ("getPromptThumbnails" in node) {
const thumbsToAdd = (node as ComfyGraphNode).getPromptThumbnails(); const thumbsToAdd = (node as ComfyGraphNode).getPromptThumbnails();
console.warn("THUMBNAILS", thumbsToAdd)
if (thumbsToAdd) if (thumbsToAdd)
thumbnails.push(...thumbsToAdd) thumbnails.push(...thumbsToAdd)
} }

View File

@@ -220,6 +220,26 @@
} }
} }
async function openGraph(cb: () => void) {
const newGraphSize = Math.max(50, graphSize);
const willOpenPane = newGraphSize != graphSize
graphSize = newGraphSize
if (willOpenPane) {
const graphPane = getGraphPane();
if (graphPane) {
graphPane.addEventListener("transitionend", cb, { once: true })
await tick()
}
else {
cb()
}
}
else {
cb()
}
}
async function showError(promptIDWithError: PromptID) { async function showError(promptIDWithError: PromptID) {
hideError(); hideError();
@@ -247,23 +267,7 @@
app.lCanvas.jumpToFirstError(); app.lCanvas.jumpToFirstError();
} }
const newGraphSize = Math.max(50, graphSize); await openGraph(jumpToError)
const willOpenPane = newGraphSize != graphSize
graphSize = newGraphSize
if (willOpenPane) {
const graphPane = getGraphPane();
if (graphPane) {
graphPane.addEventListener("transitionend", jumpToError, { once: true })
await tick()
}
else {
jumpToError()
}
}
else {
jumpToError()
}
} }
function hideError() { function hideError() {
@@ -273,7 +277,8 @@
} }
setContext(WORKFLOWS_VIEW, { setContext(WORKFLOWS_VIEW, {
showError showError,
openGraph
}); });
</script> </script>

View File

@@ -68,88 +68,91 @@
<div class="error-list-header"> <div class="error-list-header">
<button class="error-list-close" on:click={closeList}>✕</button> <button class="error-list-close" on:click={closeList}>✕</button>
</div> </div>
{#each Object.entries(errors.errorsByID) as [nodeID, nodeErrors]} <div class="error-list-scroll-container">
{@const first = nodeErrors[0]} {#each Object.entries(errors.errorsByID) as [nodeID, nodeErrors], i}
{@const parent = getParentNode(first)} {@const first = nodeErrors[0]}
<div class="error-group"> {@const parent = getParentNode(first)}
<div class="error-node-details"> {@const last = i === Object.keys(errors.errorsByID).length - 1}
<span class="error-node-type">{first.comfyNodeType}</span> <div class="error-group">
{#if parent} <div class="error-node-details">
<span class="error-node-parent">({parent.title})</span> <span class="error-node-type">{first.comfyNodeType}</span>
{/if} {#if parent}
</div> <span class="error-node-parent">({parent.title})</span>
<div class="error-entries"> {/if}
{#each nodeErrors as error} </div>
{@const isExecutionError = error.errorType === "execution"} <div class="error-entries" class:last>
<div class="error-entry"> {#each nodeErrors as error}
<div> {@const isExecutionError = error.errorType === "execution"}
<div class="error-details"> <div class="error-entry">
<button class="jump-to-error" class:execution-error={isExecutionError} on:click={() => jumpToError(error)}><span></span></button> <div>
<div class="error-details-wrapper"> <div class="error-details">
<span class="error-message" class:execution-error={isExecutionError}>{error.message}</span> <button class="jump-to-error" class:execution-error={isExecutionError} on:click={() => jumpToError(error)}><span></span></button>
{#if error.exceptionType} <div class="error-details-wrapper">
<span>({error.exceptionType})</span> <span class="error-message" class:execution-error={isExecutionError}>{error.message}</span>
{/if} {#if error.exceptionType}
{#if error.exceptionMessage && !isExecutionError} <span>({error.exceptionType})</span>
<div style:text-decoration="underline">{error.exceptionMessage}</div> {/if}
{/if} {#if error.exceptionMessage && !isExecutionError}
{#if error.input} <div style:text-decoration="underline">{error.exceptionMessage}</div>
<div class="error-input"> {/if}
<span>Input: <b>{error.input.name}</b></span> {#if error.input}
{#if error.input.config} <div class="error-input">
<span>({getInputTypeName(error.input.config[0])})</span> <span>Input: <b>{error.input.name}</b></span>
{#if error.input.config}
<span>({getInputTypeName(error.input.config[0])})</span>
{/if}
</div>
{#if canJumpToDisconnectedInput(error)}
<div style:display="flex" style:flex-direction="row">
<button class="jump-to-error locate" on:click={() => jumpToDisconnectedInput(error)}><span></span></button>
<span>Find disconnected input</span>
</div>
{/if} {/if}
</div>
{#if canJumpToDisconnectedInput(error)}
<div style:display="flex" style:flex-direction="row">
<button class="jump-to-error locate" on:click={() => jumpToDisconnectedInput(error)}><span></span></button>
<span>Find disconnected input</span>
</div>
{/if}
{#if error.input.receivedValue} {#if error.input.receivedValue}
<div> <div>
<span>Received value: <b>{error.input.receivedValue}</b></span> <span>Received value: <b>{error.input.receivedValue}</b></span>
</div> </div>
{/if} {/if}
{#if error.input.receivedType} {#if error.input.receivedType}
<div> <div>
<span>Received type: <b>{error.input.receivedType}</b></span> <span>Received type: <b>{error.input.receivedType}</b></span>
</div> </div>
{/if} {/if}
{#if error.input.config} {#if error.input.config}
<div class="error-traceback-wrapper"> <div class="error-traceback-wrapper">
<Accordion label="Input Config" open={true}> <Accordion label="Input Config" open={true}>
<div class="error-traceback"> <div class="error-traceback">
<div class="error-traceback-contents"> <div class="error-traceback-contents">
<JsonView json={error.input.config[1]} /> <JsonView json={error.input.config[1]} />
</div>
</div> </div>
</div> </Accordion>
</Accordion> </div>
</div> {/if}
{/if} {/if}
{/if} </div>
</div> </div>
</div> </div>
</div> {#if error.traceback}
{#if error.traceback} <div class="error-traceback-wrapper">
<div class="error-traceback-wrapper"> <Accordion label="Traceback" open={false}>
<Accordion label="Traceback" open={false}> <div class="error-traceback">
<div class="error-traceback"> <div class="error-traceback-contents">
<div class="error-traceback-contents"> {#each error.traceback as line}
{#each error.traceback as line} <pre>{line}</pre>
<pre>{line}</pre> {/each}
{/each} </div>
</div> </div>
</div> </Accordion>
</Accordion> </div>
</div> {/if}
{/if} </div>
</div> {/each}
{/each} </div>
</div> </div>
</div> {/each}
{/each} </div>
</div> </div>
<style lang="scss"> <style lang="scss">
@@ -158,7 +161,6 @@
width: 30%; width: 30%;
height: 70%; height: 70%;
margin: 1.0rem; margin: 1.0rem;
overflow-y: auto;
position: absolute; position: absolute;
right: 0; right: 0;
bottom: 0; bottom: 0;
@@ -186,6 +188,11 @@
} }
} }
.error-list-scroll-container {
height: calc(100% - 24px);
overflow-y: auto;
}
.error-node-details { .error-node-details {
font-size: 14pt; font-size: 14pt;
color: #ddd; color: #ddd;
@@ -200,7 +207,7 @@
font-weight: initial; font-weight: initial;
} }
.error-entries:last-child { .error-entries:not(.last):last-child {
border-bottom: 1px solid #ccc; border-bottom: 1px solid #ccc;
} }

View File

@@ -15,7 +15,8 @@
import ComfyProperties from "./ComfyProperties.svelte"; import ComfyProperties from "./ComfyProperties.svelte";
import ComfyQueue from "./ComfyQueue.svelte"; import ComfyQueue from "./ComfyQueue.svelte";
import ComfyTemplates from "./ComfyTemplates.svelte"; import ComfyTemplates from "./ComfyTemplates.svelte";
import { SvelteComponent } from "svelte"; import { SvelteComponent } from "svelte";
import { capitalize } from "$lib/utils";
export let app: ComfyApp export let app: ComfyApp
export let mode: ComfyPaneMode = "none"; export let mode: ComfyPaneMode = "none";
@@ -40,7 +41,7 @@
{:else if mode === "graph"} {:else if mode === "graph"}
<ComfyGraphView {app} /> <ComfyGraphView {app} />
{:else if mode === "properties"} {:else if mode === "properties"}
<ComfyProperties workflow={$workflowState.activeWorkflow} /> <ComfyProperties {app} workflow={$workflowState.activeWorkflow} />
{:else if mode === "templates"} {:else if mode === "templates"}
<ComfyTemplates {app} /> <ComfyTemplates {app} />
{:else if mode === "queue"} {:else if mode === "queue"}
@@ -55,6 +56,7 @@
<!-- svelte-ignore a11y-click-events-have-key-events --> <!-- svelte-ignore a11y-click-events-have-key-events -->
<button class="mode-button ternary" <button class="mode-button ternary"
disabled={mode === theMode} disabled={mode === theMode}
title={capitalize(theMode)}
class:selected={mode === theMode} class:selected={mode === theMode}
on:click={() => switchMode(theMode)}> on:click={() => switchMode(theMode)}>
<svelte:component this={icon} width="100%" height="100%" /> <svelte:component this={icon} width="100%" height="100%" />
@@ -99,7 +101,6 @@
color: var(--body-text-color); color: var(--body-text-color);
} }
&.selected { &.selected {
color: var(--body-text-color);
background-color: var(--panel-background-fill); background-color: var(--panel-background-fill);
} }
} }

View File

@@ -4,6 +4,7 @@
import { LGraphNode } from "@litegraph-ts/core" import { LGraphNode } from "@litegraph-ts/core"
import { type IDragItem, type WidgetLayout, ALL_ATTRIBUTES, type AttributesSpec, type WritableLayoutStateStore } from "$lib/stores/layoutStates" import { type IDragItem, type WidgetLayout, ALL_ATTRIBUTES, type AttributesSpec, type WritableLayoutStateStore } from "$lib/stores/layoutStates"
import uiState from "$lib/stores/uiState" import uiState from "$lib/stores/uiState"
import interfaceState from "$lib/stores/interfaceState"
import workflowState from "$lib/stores/workflowState" import workflowState from "$lib/stores/workflowState"
import layoutStates from "$lib/stores/layoutStates" import layoutStates from "$lib/stores/layoutStates"
import selectionState from "$lib/stores/selectionState" import selectionState from "$lib/stores/selectionState"
@@ -11,8 +12,12 @@
import ComfyNumberProperty from "./ComfyNumberProperty.svelte"; import ComfyNumberProperty from "./ComfyNumberProperty.svelte";
import ComfyComboProperty from "./ComfyComboProperty.svelte"; import ComfyComboProperty from "./ComfyComboProperty.svelte";
import type { ComfyWidgetNode } from "$lib/nodes/widgets"; import type { ComfyWidgetNode } from "$lib/nodes/widgets";
import type { ComfyBoxWorkflow } from "$lib/stores/workflowState"; import type { ComfyBoxWorkflow } from "$lib/stores/workflowState";
import { Diagram3 } from "svelte-bootstrap-icons";
import { getContext } from "svelte";
import { WORKFLOWS_VIEW } from "./ComfyBoxWorkflowsView.svelte";
export let app: ComfyApp
export let workflow: ComfyBoxWorkflow | null; export let workflow: ComfyBoxWorkflow | null;
let layoutState: WritableLayoutStateStore | null = null let layoutState: WritableLayoutStateStore | null = null
@@ -22,30 +27,44 @@
let target: IDragItem | null = null; let target: IDragItem | null = null;
let node: LGraphNode | null = null; let node: LGraphNode | null = null;
$: if (layoutState) { $: {
if ($selectionState.currentSelection.length > 0) { if ($interfaceState.isJumpingToNode) {
node = null; $interfaceState.isJumpingToNode = false;
const targetId = $selectionState.currentSelection.slice(-1)[0] }
const entry = $layoutState.allItems[targetId] {
if (entry != null) { if (layoutState) {
target = entry.dragItem if ($selectionState.currentSelection.length > 0) {
if (target.type === "widget") { node = null;
node = (target as WidgetLayout).node const targetId = $selectionState.currentSelection.slice(-1)[0]
const entry = $layoutState.allItems[targetId]
if (entry != null) {
target = entry.dragItem
if (target.type === "widget") {
node = (target as WidgetLayout).node
}
}
}
else if ($selectionState.currentSelectionNodes.length > 0) {
target = null;
node = $selectionState.currentSelectionNodes[0]
if (node != null && layoutState != null) {
const dragItem = layoutState.findLayoutForNode(node.id);
if (dragItem != null) {
target = dragItem;
}
}
}
else {
target = null
node = null;
} }
} }
else {
target = null;
node = null;
}
} }
else if ($selectionState.currentSelectionNodes.length > 0) {
target = null;
node = $selectionState.currentSelectionNodes[0]
}
else {
target = null
node = null;
}
}
else {
target = null;
node = null;
} }
$: if (target) { $: if (target) {
@@ -291,195 +310,244 @@
console.warn("[ComfyProperties] doRefreshPanel") console.warn("[ComfyProperties] doRefreshPanel")
$layoutStates.refreshPropsPanel += 1; $layoutStates.refreshPropsPanel += 1;
} }
const workflowsViewContext = getContext(WORKFLOWS_VIEW) as any;
async function jumpToNode() {
if (!workflowsViewContext) {
// strange svelte bug caused by HMR
// https://github.com/sveltejs/svelte/issues/8655
console.error("[ComfyProperties] No workflows view context!")
return;
}
if (app?.lCanvas == null || workflow == null || node == null)
return;
const activeWorkflow = workflowState.setActiveWorkflow(app.lCanvas, workflow.id);
if (activeWorkflow == null || !activeWorkflow.graph.getNodeByIdRecursive(node.id))
return;
await workflowsViewContext.openGraph(() => {
app.lCanvas.jumpToNode(node);
})
}
</script> </script>
<div class="props"> <div class="props">
<div class="top"> <div class="props-scroller">
<div class="target-name"> <div class="top">
<span> <div class="target-name">
<span class="title">{target?.attrs?.title || node?.title || "Workflow"}<span> <div class="target-title-wrapper">
<span class="title">{target?.attrs?.title || node?.title || "Workflow"}</span>
{#if targetType !== ""} {#if targetType !== ""}
<span class="type">({targetType})</span> <span class="type">({targetType})</span>
{/if} {/if}
</span> </div>
</span> {#if node != null}
<div class="target-name-button">
<button class="mode-button ternary"
disabled={node == null}
title="View in Graph"
on:click={jumpToNode}
>
<Diagram3 width="100%" height="100%" />
</button>
</div>
{/if}
</div>
</div> </div>
</div> <div class="props-entries">
<div class="props-entries"> {#if workflow != null && layoutState != null}
{#if workflow != null && layoutState != null} {#key workflow.id}
{#key workflow.id} {#key $layoutStates.refreshPropsPanel}
{#key $layoutStates.refreshPropsPanel} {#each ALL_ATTRIBUTES as category(category.categoryName)}
{#each ALL_ATTRIBUTES as category(category.categoryName)} <div class="category-name">
<div class="category-name"> <span>
<span> <span class="title">{category.categoryName}</span>
<span class="title">{category.categoryName}</span> </span>
</span> </div>
</div> {#each category.specs as spec(spec.id)}
{#each category.specs as spec(spec.id)} {#if validWidgetAttribute(spec, target)}
{#if validWidgetAttribute(spec, target)} <div class="props-entry">
<div class="props-entry"> {#if spec.type === "string"}
{#if spec.type === "string"} <TextBox
<TextBox
value={getAttribute(target, spec)}
on:change={(e) => updateAttribute(spec, target, e.detail)}
on:input={(e) => updateAttribute(spec, target, e.detail)}
disabled={!$uiState.uiUnlocked || !spec.editable}
label={spec.name}
max_lines={spec.multiline ? 5 : 1}
/>
{:else if spec.type === "boolean"}
<Checkbox
value={getAttribute(target, spec)} value={getAttribute(target, spec)}
on:change={(e) => updateAttribute(spec, target, e.detail)} on:change={(e) => updateAttribute(spec, target, e.detail)}
on:input={(e) => updateAttribute(spec, target, e.detail)}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
label={spec.name} label={spec.name}
max_lines={spec.multiline ? 5 : 1}
/> />
{:else if spec.type === "number"} {:else if spec.type === "boolean"}
<ComfyNumberProperty <Checkbox
name={spec.name}
value={getAttribute(target, spec)} value={getAttribute(target, spec)}
step={spec.step || 1}
min={spec.min || -1024}
max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateAttribute(spec, target, e.detail)} on:change={(e) => updateAttribute(spec, target, e.detail)}
disabled={!$uiState.uiUnlocked || !spec.editable}
label={spec.name}
/> />
{:else if spec.type === "enum"} {:else if spec.type === "number"}
<ComfyComboProperty <ComfyNumberProperty
name={spec.name} name={spec.name}
value={getAttribute(target, spec)} value={getAttribute(target, spec)}
values={spec.values} step={spec.step || 1}
min={spec.min || -1024}
max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateAttribute(spec, target, e.detail)} on:change={(e) => updateAttribute(spec, target, e.detail)}
/> />
{/if}
</div>
{:else if node}
{#if validNodeProperty(spec, node)}
<div class="props-entry">
{#if spec.type === "string"}
<TextBox
value={getProperty(node, spec)}
on:change={(e) => updateProperty(spec, e.detail)}
on:input={(e) => updateProperty(spec, e.detail)}
label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable}
max_lines={spec.multiline ? 5 : 1}
/>
{:else if spec.type === "boolean"}
<Checkbox
value={getProperty(node, spec)}
label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateProperty(spec, e.detail)}
/>
{:else if spec.type === "number"}
<ComfyNumberProperty
name={spec.name}
value={getProperty(node, spec)}
step={spec.step || 1}
min={spec.min || -1024}
max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateProperty(spec, e.detail)}
/>
{:else if spec.type === "enum"} {:else if spec.type === "enum"}
<ComfyComboProperty <ComfyComboProperty
name={spec.name} name={spec.name}
value={getProperty(node, spec)} value={getAttribute(target, spec)}
values={spec.values} values={spec.values}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateProperty(spec, e.detail)} on:change={(e) => updateAttribute(spec, target, e.detail)}
/> />
{/if} {/if}
</div> </div>
{:else if validNodeVar(spec, node)} {:else if node}
{#if validNodeProperty(spec, node)}
<div class="props-entry">
{#if spec.type === "string"}
<TextBox
value={getProperty(node, spec)}
on:change={(e) => updateProperty(spec, e.detail)}
on:input={(e) => updateProperty(spec, e.detail)}
label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable}
max_lines={spec.multiline ? 5 : 1}
/>
{:else if spec.type === "boolean"}
<Checkbox
value={getProperty(node, spec)}
label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateProperty(spec, e.detail)}
/>
{:else if spec.type === "number"}
<ComfyNumberProperty
name={spec.name}
value={getProperty(node, spec)}
step={spec.step || 1}
min={spec.min || -1024}
max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateProperty(spec, e.detail)}
/>
{:else if spec.type === "enum"}
<ComfyComboProperty
name={spec.name}
value={getProperty(node, spec)}
values={spec.values}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateProperty(spec, e.detail)}
/>
{/if}
</div>
{:else if validNodeVar(spec, node)}
<div class="props-entry">
{#if spec.type === "string"}
<TextBox
value={getVar(node, spec)}
on:change={(e) => updateVar(spec, e.detail)}
on:input={(e) => updateVar(spec, e.detail)}
label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable}
max_lines={spec.multiline ? 5 : 1}
/>
{:else if spec.type === "boolean"}
<Checkbox
value={getVar(node, spec)}
on:change={(e) => updateVar(spec, e.detail)}
disabled={!$uiState.uiUnlocked || !spec.editable}
label={spec.name}
/>
{:else if spec.type === "number"}
<ComfyNumberProperty
name={spec.name}
value={getVar(node, spec)}
step={spec.step || 1}
min={spec.min || -1024}
max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateVar(spec, e.detail)}
/>
{:else if spec.type === "enum"}
<ComfyComboProperty
name={spec.name}
value={getVar(node, spec)}
values={spec.values}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateVar(spec, e.detail)}
/>
{/if}
</div>
{/if}
{:else if !node && !target && validWorkflowAttribute(spec)}
<div class="props-entry"> <div class="props-entry">
{#if spec.type === "string"} {#if spec.type === "string"}
<TextBox <TextBox
value={getVar(node, spec)} value={getWorkflowAttribute(spec)}
on:change={(e) => updateVar(spec, e.detail)} on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
on:input={(e) => updateVar(spec, e.detail)} on:input={(e) => updateWorkflowAttribute(spec, e.detail)}
label={spec.name} label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
max_lines={spec.multiline ? 5 : 1} max_lines={spec.multiline ? 5 : 1}
/> />
{:else if spec.type === "boolean"} {:else if spec.type === "boolean"}
<Checkbox <Checkbox
value={getVar(node, spec)} value={getWorkflowAttribute(spec)}
on:change={(e) => updateVar(spec, e.detail)} on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
label={spec.name} label={spec.name}
/> />
{:else if spec.type === "number"} {:else if spec.type === "number"}
<ComfyNumberProperty <ComfyNumberProperty
name={spec.name} name={spec.name}
value={getVar(node, spec)} value={getWorkflowAttribute(spec)}
step={spec.step || 1} step={spec.step || 1}
min={spec.min || -1024} min={spec.min || -1024}
max={spec.max || 1024} max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateVar(spec, e.detail)} on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
/> />
{:else if spec.type === "enum"} {:else if spec.type === "enum"}
<ComfyComboProperty <ComfyComboProperty
name={spec.name} name={spec.name}
value={getVar(node, spec)} value={getWorkflowAttribute(spec)}
values={spec.values} values={spec.values}
disabled={!$uiState.uiUnlocked || !spec.editable} disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateVar(spec, e.detail)} on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
/> />
{/if} {/if}
</div> </div>
{:else if !node && !target && validWorkflowAttribute(spec)} {/if}
<div class="props-entry">
{#if spec.type === "string"}
<TextBox
value={getWorkflowAttribute(spec)}
on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
on:input={(e) => updateWorkflowAttribute(spec, e.detail)}
label={spec.name}
disabled={!$uiState.uiUnlocked || !spec.editable}
max_lines={spec.multiline ? 5 : 1}
/>
{:else if spec.type === "boolean"}
<Checkbox
value={getWorkflowAttribute(spec)}
on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
disabled={!$uiState.uiUnlocked || !spec.editable}
label={spec.name}
/>
{:else if spec.type === "number"}
<ComfyNumberProperty
name={spec.name}
value={getWorkflowAttribute(spec)}
step={spec.step || 1}
min={spec.min || -1024}
max={spec.max || 1024}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
/>
{:else if spec.type === "enum"}
<ComfyComboProperty
name={spec.name}
value={getWorkflowAttribute(spec)}
values={spec.values}
disabled={!$uiState.uiUnlocked || !spec.editable}
on:change={(e) => updateWorkflowAttribute(spec, e.detail)}
/>
{/if}
</div>
{/each} {/each}
{/each} {/each}
{/key} {/key}
{/key} {/key}
{/key} {/if}
</div> </div>
</div> </div>
</div> </div>
<style lang="scss">
$bottom-bar-height: 2.5rem;
.props {
width: 100%;
height: 100%;
}
.props-scroller {
width: 100%;
height: calc(100% - $bottom-bar-height);
overflow-x: hidden;
overflow-y: auto;
}
.props-entry { .props-entry {
padding-bottom: 0.5rem; padding-bottom: 0.5rem;
@@ -491,7 +559,7 @@
.target-name { .target-name {
background: var(--input-background-fill); background: var(--input-background-fill);
border-color: var(--input-border-color); border-color: var(--input-border-color);
white-space: nowrap; white-space: nowrap;
.title { .title {
@@ -501,6 +569,48 @@
padding-left: 0.25rem; padding-left: 0.25rem;
font-weight: normal; font-weight: normal;
} }
}
width: 100%;
display: flex;
flex-direction: row;
> .target-title-wrapper {
padding: 0.8rem 0 0.8rem 1.0rem;
display: flex;
flex-direction: row;
width: 100%;
text-align: center;
> span {
display: flex;
flex-direction: column;
justify-content: center;
}
}
> .target-name-button {
padding: 0.5rem;
.mode-button {
color: var(--comfy-accent-soft);
height: $bottom-bar-height;
width: 2.5rem;
height: 2.5rem;
margin: 1.0rem;
padding: 0.5rem;
margin-left: auto;
@include square-button;
color: var(--neutral-300);
&:hover:not(:disabled) {
filter: brightness(120%) !important;
}
&:active:not(:disabled) {
filter: brightness(50%) !important;
}
}
} }
} }
@@ -518,13 +628,5 @@
color: var(--neutral-500); color: var(--neutral-500);
} }
} }
.bottom {
/* width: 100%;
height: auto;
position: absolute;
bottom: 0;
padding: 0.5em; */
}
@include disable-inputs; @include disable-inputs;

View File

@@ -146,10 +146,10 @@
if (entry.extraData?.workflowTitle != null) { if (entry.extraData?.workflowTitle != null) {
message = `${entry.extraData.workflowTitle}` message = `${entry.extraData.workflowTitle}`
} }
if (subgraphs) {
if (subgraphs && subgraphs.length > 0) {
const subgraphsString = subgraphs.join(', ') const subgraphsString = subgraphs.join(', ')
if (subgraphsString.length > 0) message += ` (${subgraphsString})`
message += ` (${subgraphsString})`
} }
let submessage = `Nodes: ${Object.keys(entry.prompt).length}` let submessage = `Nodes: ${Object.keys(entry.prompt).length}`

View File

@@ -0,0 +1,260 @@
<script lang="ts">
import { CONFIG_CATEGORIES, CONFIG_DEFS_BY_CATEGORY, CONFIG_DEFS_BY_NAME, type ConfigDefAny, type ConfigDefEnum, type ConfigState } from "$lib/stores/configDefs";
import { capitalize } from "$lib/utils";
import { Checkbox } from "@gradio/form";
import configState from "$lib/stores/configState";
import type ComfyApp from "./ComfyApp";
import NumberInput from "./NumberInput.svelte";
import Textbox from "@gradio/form/src/Textbox.svelte";
import { Button } from "@gradio/button";
import { SvelteToast } from "@zerodevx/svelte-toast";
import notify from "$lib/notify";
export let app: ComfyApp
let selectedCategory = CONFIG_CATEGORIES[0];
let changes: Partial<Record<keyof ConfigState, any>> = {}
const toastOptions = {
intro: { duration: 200 },
theme: {
'--toastBarHeight': 0
}
}
function selectCategory(category: string) {
selectedCategory = category;
}
function setOption(def: ConfigDefAny, value: any) {
if (!configState.validateConfigOption(def, value)) {
console.warn(`[configState] Invalid value for option ${def.name} (${value}), setting to default (${def.defaultValue})`);
value = def.defaultValue
}
changes[def.name] = value;
}
function setEnumOption(def: ConfigDefEnum<any, any>, e: Event): void {
const select = e.target as HTMLSelectElement;
const index = select.selectedIndex
setOption(def, def.options.values[index].value)
}
function doSave() {
for (const [k, v] of Object.entries(changes)) {
const def = CONFIG_DEFS_BY_NAME[k]
configState.setConfigOption(def, v, true);
}
changes = {};
const json = JSON.stringify($configState);
localStorage.setItem("config", json);
notify("Config applied!", { type: "success" })
}
function doReset() {
if (!confirm("Are you sure you want to reset the config to the defaults?"))
return;
configState.loadDefault(true);
notify("Config reset!")
}
</script>
<div class="comfy-settings">
<div class="comfy-settings-categories">
{#each CONFIG_CATEGORIES as category}
<!-- svelte-ignore a11y-click-events-have-key-events -->
<div class="comfy-settings-category" class:selected={selectedCategory === category} on:click={() => selectCategory(category)}>
{capitalize(category)}
</div>
{/each}
</div>
<div class="comfy-settings-main">
{#if selectedCategory}
{@const categoryDefs = CONFIG_DEFS_BY_CATEGORY[selectedCategory]}
{#key $configState}
<div class="comfy-settings-entries">
{#each categoryDefs as def}
{@const value = $configState[def.name]}
<div class="comfy-settings-entry">
<div class="name">{def.name}</div>
{#if def.type === "boolean"}
<span class="ctrl checkbox">
<Checkbox label={def.description} {value} on:change={(e) => setOption(def, e.detail)} />
</span>
{:else if def.type === "number"}
<div class="description">{def.description}</div>
<span class="ctrl number">
<NumberInput label="" min={def.options.min} max={def.options.max} step={def.options.step} {value} on:release={(e) => setOption(def, e.detail)} />
</span>
{:else if def.type === "string"}
<div class="description">{def.description}</div>
<span class="ctrl textbox">
<Textbox label="" lines={1} max_lines={1} {value} on:change={(e) => setOption(def, e.detail)} />
</span>
{:else if def.type === "string[]"}
<div class="description">{def.description}</div>
<span class="ctrl string-array">
{value.join(",")}
</span>
{:else if def.type === "enum"}
<div class="description">{def.description}</div>
<span class="ctrl enum">
<select id="ui-theme" name="ui-theme" on:change={(e) => setEnumOption(def, e)}>
{#each def.options.values as option, i}
{@const selected = def.options.values[i].value === value}
<option value={option.value} {selected}>{option.label}</option>
{/each}
</select>
</span>
{:else}
(Unknown config type {def.type})
{/if}
</div>
{/each}
</div>
{/key}
{:else}
Please select a category.
{/if}
<div class="comfy-settings-bottom-bar">
<div>
<div class="left">
<Button variant="secondary" on:click={doReset}>
Reset
</Button>
</div>
<div class="right">
<Button variant="primary" on:click={doSave}>
Save
</Button>
</div>
</div>
</div>
</div>
<SvelteToast options={toastOptions} />
</div>
<style lang="scss">
$bottom-bar-height: 5rem;
.comfy-settings {
color: var(--body-text-color);
display: flex;
flex-direction: row;
width: 100%;
height: 100%;
}
.comfy-settings-categories {
width: 20rem;
height: 100%;
color: var(--neutral-500);
background: var(--neutral-800);
border-left: 2px solid var(--comfy-splitpanes-background-fill);
}
.comfy-settings-category {
padding: 2rem 3rem;
font-size: 14pt;
border-bottom: 1px solid grey;
cursor: pointer;
&.selected {
color: var(--body-text-color);
background: var(--neutral-700);
}
}
.comfy-settings-main {
width: 100%;
height: calc(100% - $bottom-bar-height);
}
.comfy-settings-entries {
padding: 3rem 3rem;
height: 100%;
}
.comfy-settings-entry {
padding: 1rem 3rem;
.name {
font-weight: bold;
font-size: 13pt;
}
.description {
font-size: 11pt;
color: var(--neutral-400);
}
.ctrl {
margin-top: 0.5rem;
min-width: 5rem;
display: block;
&:not(.checkbox) {
width: 20rem;
}
&.textbox {
:global(span) {
display: block !important;
}
}
&.checkbox {
display: inline-flex !important;
padding: 0 0.75rem;
:global(label) {
color: var(--neutral-400);
font-size: 11pt;
}
}
&.enum {
select {
-webkit-appearance: none;
-moz-appearance: none;
background-image: url("data:image/svg+xml;utf8,<svg fill='white' height='24' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/><path d='M0 0h24v24H0z' fill='none'/></svg>");
background-repeat: no-repeat;
background-position-x: 100%;
background-position-y: 8px;
}
}
}
}
.comfy-settings-bottom-bar {
background: var(--neutral-900);
width: 100%;
border-top: 2px solid var(--neutral-800);
gap: var(--layout-gap);
overflow-x: hidden;
height: $bottom-bar-height;
justify-content: center;
padding: 0 2rem;
margin: auto;
position: relative;
flex-direction: column;
display: flex;
> div {
width: 100%;
display: flex;
gap: var(--layout-gap);
margin: auto;
flex-wrap: nowrap;
}
.left {
left: 0;
}
.right {
margin-left: auto;
}
}
</style>

View File

@@ -3,7 +3,7 @@
import type { ComfyImageLocation } from "$lib/nodes/ComfyWidgetNodes"; import type { ComfyImageLocation } from "$lib/nodes/ComfyWidgetNodes";
import notify from "$lib/notify"; import notify from "$lib/notify";
import configState from "$lib/stores/configState"; import configState from "$lib/stores/configState";
import { convertComfyOutputEntryToGradio, convertComfyOutputToComfyURL, type ComfyUploadImageAPIResponse } from "$lib/utils"; import { batchUploadFilesToComfyUI, convertComfyOutputToComfyURL, type ComfyBatchUploadResult } from "$lib/utils";
import { Block, BlockLabel } from "@gradio/atoms"; import { Block, BlockLabel } from "@gradio/atoms";
import { File as FileIcon } from "@gradio/icons"; import { File as FileIcon } from "@gradio/icons";
import type { FileData as GradioFileData } from "@gradio/upload"; import type { FileData as GradioFileData } from "@gradio/upload";
@@ -59,55 +59,10 @@
dispatch("image_clicked") dispatch("image_clicked")
} }
interface GradioUploadResponse { async function upload_files(files: Array<File>): Promise<ComfyBatchUploadResult> {
error?: string; console.debug("UPLOADFILES", files);
files?: Array<ComfyImageLocation>;
}
async function upload_files(root: string, files: Array<File>): Promise<GradioUploadResponse> {
console.debug("UPLOADILFES", root, files);
dispatch("uploading") dispatch("uploading")
return batchUploadFilesToComfyUI(files);
const url = configState.getBackendURL();
const requests = files.map(async (file) => {
const formData = new FormData();
formData.append("image", file, file.name);
return fetch(new Request(url + "/upload/image", {
body: formData,
method: 'POST'
}))
.then(r => r.json())
.catch(error => error);
});
return Promise.all(requests)
.then( (results) => {
const errors = []
const files = []
for (const r of results) {
if (r instanceof Error) {
errors.push(r.toString())
}
else {
// bare filename of image
const resp = r as ComfyUploadImageAPIResponse;
files.push({
filename: resp.name,
subfolder: "",
type: "input"
})
}
}
let error = null;
if (errors && errors.length > 0)
error = "Upload error(s):\n" + errors.join("\n");
return { error, files }
})
} }
$: { $: {
@@ -144,7 +99,7 @@
); );
let upload_value = _value; let upload_value = _value;
pending_upload = true; pending_upload = true;
upload_files(root, files).then((response) => { upload_files(files).then((response) => {
if (JSON.stringify(upload_value) !== JSON.stringify(_value)) { if (JSON.stringify(upload_value) !== JSON.stringify(_value)) {
// value has changed since upload started // value has changed since upload started
console.error("[ImageUpload] value has changed since upload started", upload_value, _value) console.error("[ImageUpload] value has changed since upload started", upload_value, _value)

View File

@@ -41,7 +41,7 @@
#lightboxModal{ #lightboxModal{
display: none; display: none;
position: fixed; position: fixed;
z-index: 1001; z-index: var(--layer-top);
left: 0; left: 0;
top: 0; top: 0;
width: 100%; width: 100%;

View File

@@ -0,0 +1,669 @@
<script context="module" lang="ts">
export type MaskCanvasData = {
hasMask: boolean,
maskCanvas: HTMLCanvasElement | null,
curLineGroup: LineGroup,
redoCurLines: LineGroup,
}
export type LinePoint = {
x: number,
y: number
}
export interface Line {
size?: number,
points: LinePoint[]
}
export type LineGroup = Line[];
</script>
<script lang="ts">
import { loadImage } from "$lib/widgets/utils"
import { tick, createEventDispatcher } from "svelte";
import { ArrowClockwise, ArrowCounterclockwise, XSquare, Exclude, Circle, Grid3x3Gap, ArrowsFullscreen, FullscreenExit } from "svelte-bootstrap-icons";
export let fileURL: string | null = null;
export let fullscreen: boolean = false;
const dispatch = createEventDispatcher<{
change: MaskCanvasData;
release: MaskCanvasData;
loaded: MaskCanvasData
}>();
let canvasCursor: string | undefined = undefined;
let container: HTMLDivElement | null;
let canvas: HTMLCanvasElement | null;
let maskCanvas: HTMLCanvasElement | null;
let renders: HTMLImageElement[] = [];
let context: CanvasRenderingContext2D | null;
let maskContext: CanvasRenderingContext2D | null;
let curLineGroup: LineGroup = [];
let redoCurLines: LineGroup = []
let original: HTMLImageElement | null;
let isImageLoaded: boolean = false;
let imageWidth: number = 512;
let imageHeight: number = 512;
let scale: number = 1.0;
let minScale: number = 1.0;
let brushSize: number = 100;
let maskBlur: number = 0;
let clipMask: boolean = false;
let hasMask: boolean = false;
let isDrawing: boolean = false;
let isPanning: boolean = false;
let isBrushShowing: boolean = false;
let transform = ""
$: transform = `translate(${imx}px, ${imy}px) scale(${scale})`
let imx: number = 0;
let imy: number = 0;
let x: number = 0;
let y: number = 0;
let panX: number = 0;
let panY: number = 0;
const BRUSH_COLOR = "#000"
enum MouseButton {
Left = 0,
Middle = 1,
Right = 2,
Back = 3,
Forward = 4
}
$: if (isPanning) {
canvasCursor = "grab";
}
else if (isImageLoaded && isBrushShowing) {
canvasCursor = "none";
}
else {
canvasCursor = undefined;
}
$: {
context = canvas ? canvas.getContext("2d") : null
}
function clearState() {
hasMask = false;
maskCanvas = null;
maskContext = null;
isImageLoaded = false;
original = null;
renders = []
// curLineGroup = [];
// redoCurLines = []
imageWidth = 512;
imageHeight = 512;
scale = 1.0;
minScale = 0.5;
}
let loadedFileURL: string | null = null
let dispatchLoaded: boolean = false;
$: if (fileURL !== loadedFileURL) {
clearState();
if (fileURL) {
loadImage(fileURL).then(i => {
original = i;
isImageLoaded = true;
dispatchLoaded = true;
})
.catch(i => {
isImageLoaded = false;
})
}
else {
isImageLoaded = false;
original = null;
}
loadedFileURL = fileURL
}
$: {
// initSizeAndScale(isImageLoaded, original);
[imageWidth, imageHeight] = getCurrentWidthAndHeight(isImageLoaded, original)
scale = initScale(imageWidth, imageHeight)
initImagePos()
// in case mask strokes were preserved after new image load
// (use case: sending an inpainted image back while reusing the same mask)
tick().then(() => {
loaded();
})
}
function loaded() {
if (!dispatchLoaded)
return;
dispatchLoaded = false;
redrawCurLines()
hasMask = curLineGroup.length > 0;
console.warn("[MaskCanvas] LOADED", maskCanvas, hasMask)
dispatch("loaded", {
hasMask,
maskCanvas,
curLineGroup,
redoCurLines
})
}
$: hasMask = curLineGroup.length > 0;
function initImagePos() {
if (!container)
return
const rect = container.getBoundingClientRect();
imx = rect.width / 2 - (imageWidth / 2) * scale
imy = rect.height / 2 - (imageHeight / 2) * scale
}
function initScale(width: number, height: number): number {
const s = getScale(width, height);
minScale = s / 2;
return s;
}
function initSizeAndScale(isImageLoaded: boolean, original: HTMLImageElement | null) {
[imageWidth, imageHeight] = getCurrentWidthAndHeight(isImageLoaded, original)
scale = getScale(imageWidth, imageHeight)
minScale = scale;
}
function drawOnCurrentRender(lineGroup: LineGroup) {
draw(lineGroup)
dispatch("change", {
hasMask,
maskCanvas,
curLineGroup,
redoCurLines
})
}
function draw(lineGroup: LineGroup) {
if (!context || !maskContext)
return
context.clearRect(0, 0, context.canvas.width, context.canvas.height)
maskContext.clearRect(0, 0, maskContext.canvas.width, maskContext.canvas.height)
const color = BRUSH_COLOR
const drawMask = (ctx: CanvasRenderingContext2D) => {
ctx.save();
ctx.filter = `blur(${maskBlur}px)`
drawLines(ctx, lineGroup, color)
ctx.restore();
}
drawMask(maskContext);
if (clipMask) {
context.save();
context.filter = `blur(${maskBlur}px)`
drawLines(context, lineGroup, color)
context.restore();
context.globalCompositeOperation = "source-in"
context.drawImage(original!!, 0, 0, imageWidth, imageHeight)
context.globalCompositeOperation = "source-over";
}
else {
drawMask(context);
}
}
function updateMaskImage() {
drawOnCurrentRender(curLineGroup);
}
function drawLines(ctx: CanvasRenderingContext2D, lines: LineGroup, color: string) {
ctx.strokeStyle = color
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
lines.forEach(line => {
if (!line?.points.length || !line.size) {
return
}
ctx.lineWidth = line.size
ctx.beginPath()
ctx.moveTo(line.points[0].x, line.points[0].y)
line.points.forEach(point => ctx.lineTo(point.x, point.y))
ctx.stroke()
})
}
function redrawCurLines() {
drawOnCurrentRender(curLineGroup || [])
}
$: if (canvas && original) {
console.warn("INITCANVAS", imageWidth, imageHeight, original.src)
maskCanvas = document.createElement("canvas");
maskContext = maskCanvas.getContext("2d")!;
maskCanvas.width = imageWidth;
maskCanvas.height = imageHeight;
canvas.width = imageWidth;
canvas.height = imageHeight;
redrawCurLines() // no react on curLineGroup
}
function getCurrentWidthAndHeight(isImageLoaded: boolean, original: HTMLImageElement | null) {
if (isImageLoaded && original){
return [original.naturalWidth, original.naturalHeight]
}
return [512, 512]
}
function getScale(width: number, height: number): number {
const size = container?.getBoundingClientRect();
if (!size) {
return 1.0
}
const ratioWidth = size.width / width
const ratioHeight = (size.height) / height
let scale: number = 1.0
if (ratioWidth < 1 || ratioHeight < 1) {
scale = Math.min(ratioWidth, ratioHeight)
}
return scale
}
function undoStroke() {
if (curLineGroup.length === 0) {
return
}
const lastLine = curLineGroup.pop()!
const newRedoCurLines = [...redoCurLines, lastLine]
redoCurLines = newRedoCurLines
const newLineGroup = [...curLineGroup]
curLineGroup = newLineGroup
drawOnCurrentRender(newLineGroup)
}
function redoStroke() {
if (redoCurLines.length === 0) {
return
}
const line = redoCurLines.pop()!
redoCurLines = [...redoCurLines]
const newLineGroup = [...curLineGroup, line]
curLineGroup = newLineGroup
drawOnCurrentRender(newLineGroup)
}
export function clearStrokes() {
redoCurLines = []
const newLineGroup: LineGroup = []
curLineGroup = newLineGroup
drawOnCurrentRender(newLineGroup)
}
export function recenterImage() {
scale = initScale(imageWidth, imageHeight)
initImagePos();
}
async function toggleFullscreen() {
fullscreen = !fullscreen;
updateMaskImage();
await tick();
recenterImage();
}
function onCanvasMouseOver() {
isBrushShowing = true;
}
function onCanvasFocus() {
isBrushShowing = true;
}
function onCanvasMouseLeave() {
isBrushShowing = false;
}
function mouseXY(e: MouseEvent): LinePoint {
return { x: e.offsetX, y: e.offsetY }
}
function onCanvasMouseDown(e: MouseEvent) {
if (!original?.src)
return;
if (isPanning)
return;
if (canvas == null)
return;
switch (e.button) {
case MouseButton.Right:
return;
case MouseButton.Middle:
isPanning = true;
panX = e.offsetX * scale;
panY = e.offsetY * scale;
return;
}
isDrawing = true;
redoCurLines = []
let lineGroup: LineGroup = [...curLineGroup]
lineGroup.push({size: brushSize, points: [mouseXY(e)] })
curLineGroup = lineGroup
drawOnCurrentRender(curLineGroup);
}
function onCanvasMouseUp() {
}
function onCanvasMouseMove(e: MouseEvent) {
if (isPanning)
return;
if (!isDrawing)
return;
if (curLineGroup.length === 0)
return
curLineGroup[curLineGroup.length-1].points.push(mouseXY(e))
curLineGroup = curLineGroup; // react
drawOnCurrentRender(curLineGroup)
}
function onCanvasMouseWheel(e: WheelEvent) {
e.preventDefault();
if (!container || e.target != canvas)
return;
const bound = container.getBoundingClientRect()
// coodinates on the image that were zoomed
const x_ = e.clientX - bound.x
const y_ = e.clientY - bound.y
e.preventDefault();
var delta = e.deltaY * -0.001
delta = Math.max(-1,Math.min(1,delta)) // cap the delta to [-1,1] for cross browser consistency
const zx = (x_ - imx)/scale
const zy = (y_ - imy)/scale
scale += delta * scale
scale = Math.max(minScale,scale)
imx = -zx * scale + x_
imy = -zy * scale + y_
x = e.offsetX * scale;
y = e.offsetY * scale;
}
function onMouseMove(e: MouseEvent) {
if (e.target != canvas)
return;
x = e.offsetX * scale;
y = e.offsetY * scale;
if (isPanning) {
imx += x - panX;
imy += y - panY;
}
}
function onMouseUp(e: MouseEvent) {
if (e.button === MouseButton.Middle) {
isPanning = false
panX = 0
panY = 0
}
if (isPanning)
return;
if (!original?.src)
return;
if (!canvas)
return;
if (!isDrawing)
return;
isDrawing = false;
dispatch("release", { hasMask, maskCanvas, curLineGroup, redoCurLines })
}
function dispatchRelease() {
updateMaskImage()
dispatch("release", { hasMask, maskCanvas, curLineGroup, redoCurLines })
}
</script>
<svelte:window on:mouseup={onMouseUp} />
<div class="me-container" class:fullscreen bind:this={container} on:mousemove={onMouseMove}>
{#if !isImageLoaded}
<div>
(empty)
</div>
{:else}
<div class="me-transform" style:transform={transform} style:--scale={scale}>
<div class="me-canvas-container">
<div class="me-original-image-container"
style:width="{imageWidth}px"
style:height="{imageHeight}px">
{#if original}
{@const showOriginal = !clipMask}
<img class="me-original-image"
src={original.src}
style:width={imageWidth}
style:height={imageHeight}
style:display={showOriginal ? "block" : "none"}
/>
{/if}
</div>
<canvas class="me-canvas"
bind:this={canvas}
style:cursor={canvasCursor}
on:mouseover={onCanvasMouseOver}
on:focus={onCanvasFocus}
on:wheel={onCanvasMouseWheel}
on:mouseleave={onCanvasMouseLeave}
on:mousedown|preventDefault={onCanvasMouseDown}
on:mouseup|preventDefault={onCanvasMouseUp}
on:mousemove={onCanvasMouseMove}
/>
</div>
</div>
{/if}
{#if isImageLoaded && isBrushShowing && !isPanning}
<div class="me-brush-cursor"
style:width="{brushSize * scale}px"
style:height="{brushSize * scale}px"
style:left="{x + imx}px"
style:top="{y + imy}px"
style:transform="translate(-50%, -50%)"
/>
{/if}
<div class="me-toolkit-bar">
<button disabled={curLineGroup.length === 0} on:click={undoStroke}>
<ArrowCounterclockwise />
</button>
<button disabled={redoCurLines.length === 0} on:click={redoStroke}>
<ArrowClockwise />
</button>
<button on:click={clearStrokes} disabled={curLineGroup.length === 0 && redoCurLines.length === 0}>
<XSquare/>
</button>
<label>
<Circle />
<input type="range" min="1" max="200" bind:value={brushSize} step="0.1"
on:change={updateMaskImage}
on:pointerup={dispatchRelease}/>
</label>
<label>
<Grid3x3Gap/>
<input type="range" min="1" max="100" bind:value={maskBlur} step="0.1"
on:change={updateMaskImage}
on:pointerup={dispatchRelease}/>
</label>
<div class="toggle-button" class:toggled={clipMask} on:click={() => {clipMask = !clipMask; updateMaskImage()}}>
<Exclude />
</div>
<div class="toggle-button" class:toggled={fullscreen} on:click={() => {toggleFullscreen()}}>
{#if fullscreen}
<FullscreenExit />
{:else}
<ArrowsFullscreen />
{/if}
</div>
</div>
</div>
<style lang="scss">
$bg-color: #a0a0a0;
.me-container {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
background-color: white;
background-image:
linear-gradient(45deg, #ccc 25%, transparent 25%),
linear-gradient(135deg, #ccc 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #ccc 75%),
linear-gradient(135deg, transparent 75%, #ccc 75%);
background-size:25px 25px; /* Must be a square */
background-position:0 0, 12.5px 0, 12.5px -12.5px, 0px 12.5px; /* Must be half of one side of the square */
&.fullscreen {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
margin: auto;
z-index: var(--layer-top);
}
}
.me-transform {
--scale: 1;
display: flex;
flex-wrap: wrap;
width: -moz-fit-content;
width: fit-content;
height: -moz-fit-content;
height: fit-content;
margin: 0;
padding: 0;
transform-origin: 0% 0%;
}
.me-original-image-container {
position: absolute;
top: 0;
left: 0;
grid-area: editor-content;
pointer-events: none;
user-select: none;
display: grid;
grid-template-areas: 'original-image-content';
border: calc((1 / var(--scale)) * 5px) dashed grey;
img.me-original-image {
grid-area: original-image-content;
}
}
.me-canvas {
position: absolute;
z-index: 1;
}
.me-brush-cursor {
position: absolute;
border-radius: 50%;
background-color: #000;
border: 1px solid var(--yellow-accent);
pointer-events: none;
}
.me-toolkit-bar {
position: absolute;
bottom: 0.5rem;
border-radius: 3rem;
padding: 0.4rem 24px;
display: flex;
margin: 0.5rem auto;
gap: 16px;
left: 0;
right: 0;
width: 80%;
height: 3rem;
align-items: center;
justify-content: space-evenly;
backdrop-filter: blur(12px);
background-color: white;
animation: slideUp 0.2s ease-out;
border: var(--editor-toolkit-panel-border);
box-shadow: 0 0 0 4px #0000001a, 0 3px 16px #00000014, 0 2px 6px 1px #00000017;
label {
display: flex;
flex-direction: row;
gap: 4px;
input {
width: 5rem;
}
}
button {
&:not(:disabled) {
cursor: pointer;
}
&:hover:not(:disabled) {
color: var(--secondary-600);
}
&:disabled {
opacity: 40%;
}
}
.toggle-button {
&:hover:not(:disabled) {
color: var(--secondary-600);
}
&:not(:disabled) {
cursor: pointer;
}
&.toggled {
color: var(--secondary-400);
}
}
}
</style>

View File

@@ -4,8 +4,8 @@
import { createEventDispatcher } from "svelte"; import { createEventDispatcher } from "svelte";
export let value: number = 0; export let value: number = 0;
export let min: number = -1024 export let min: number | null = null
export let max: number = 1024 export let max: number | null = null
export let step: number = 1; export let step: number = 1;
export let label: string = ""; export let label: string = "";
export let disabled: boolean = false; export let disabled: boolean = false;
@@ -41,9 +41,11 @@
<div class="wrap"> <div class="wrap">
<div class="head"> <div class="head">
<label> {#if label}
<BlockTitle>{label}</BlockTitle> <label>
</label> <BlockTitle>{label}</BlockTitle>
</label>
{/if}
<input <input
data-testid="number-input" data-testid="number-input"
type="number" type="number"
@@ -83,11 +85,11 @@
border: var(--input-border-width) solid var(--input-border-color); border: var(--input-border-width) solid var(--input-border-color);
border-radius: var(--input-radius); border-radius: var(--input-radius);
background: var(--input-background-fill); background: var(--input-background-fill);
padding: var(--size-2) var(--size-2); padding: var(--input-padding);
color: var(--body-text-color); color: var(--body-text-color);
font-size: var(--input-text-size); font-size: var(--input-text-size);
line-height: var(--line-sm); line-height: var(--line-sm);
text-align: center; // text-align: center;
} }
input:disabled { input:disabled {
-webkit-text-fill-color: var(--body-text-color); -webkit-text-fill-color: var(--body-text-color);
@@ -95,9 +97,16 @@
opacity: 1; opacity: 1;
} }
input[type="number"]:focus { input[type="number"] {
box-shadow: var(--input-shadow-focus); &:focus {
border-color: var(--input-border-color-focus); box-shadow: var(--input-shadow-focus);
border-color: var(--input-border-color-focus);
}
&::-webkit-inner-spin-button,
&::-webkit-outer-spin-button {
opacity: 100%;
}
} }
input::placeholder { input::placeholder {
@@ -107,4 +116,5 @@
input[disabled] { input[disabled] {
cursor: not-allowed; cursor: not-allowed;
} }
</style> </style>

View File

@@ -16,3 +16,9 @@
<!-- svelte-ignore a11y-click-events-have-key-events --> <!-- svelte-ignore a11y-click-events-have-key-events -->
<div on:click={onClick}>{message}</div> <div on:click={onClick}>{message}</div>
<style lang="scss">
div {
cursor: pointer;
}
</style>

View File

@@ -1,5 +1,5 @@
import LGraphCanvas from "@litegraph-ts/core/src/LGraphCanvas"; import LGraphCanvas from "@litegraph-ts/core/src/LGraphCanvas";
import ComfyGraphNode from "./ComfyGraphNode"; import ComfyGraphNode, { type ComfyGraphNodeProperties } from "./ComfyGraphNode";
import ComfyWidgets from "$lib/widgets" import ComfyWidgets from "$lib/widgets"
import type { ComfyWidgetNode } from "$lib/nodes/widgets"; import type { ComfyWidgetNode } from "$lib/nodes/widgets";
import { BuiltInSlotShape, BuiltInSlotType, LiteGraph, type SerializedLGraphNode } from "@litegraph-ts/core"; import { BuiltInSlotShape, BuiltInSlotType, LiteGraph, type SerializedLGraphNode } from "@litegraph-ts/core";
@@ -8,10 +8,19 @@ import type { ComfyInputConfig } from "$lib/IComfyInputSlot";
import { iterateNodeDefOutputs, type ComfyNodeDef, iterateNodeDefInputs } from "$lib/ComfyNodeDef"; import { iterateNodeDefOutputs, type ComfyNodeDef, iterateNodeDefInputs } from "$lib/ComfyNodeDef";
import type { SerializedPromptOutput } from "$lib/utils"; import type { SerializedPromptOutput } from "$lib/utils";
export interface ComfyBackendNodeProperties extends ComfyGraphNodeProperties {
noOutputDisplay: boolean
}
/* /*
* Base class for any node with configuration sent by the backend. * Base class for any node with configuration sent by the backend.
*/ */
export class ComfyBackendNode extends ComfyGraphNode { export class ComfyBackendNode extends ComfyGraphNode {
override properties: ComfyBackendNodeProperties = {
tags: [],
noOutputDisplay: false
}
comfyClass: string; comfyClass: string;
comfyNodeDef: ComfyNodeDef; comfyNodeDef: ComfyNodeDef;
displayName: string | null; displayName: string | null;
@@ -37,6 +46,10 @@ export class ComfyBackendNode extends ComfyGraphNode {
} }
} }
get isOutputNode(): boolean {
return this.comfyNodeDef.output_node;
}
// comfy class -> input name -> input config // comfy class -> input name -> input config
private static defaultInputConfigs: Record<string, Record<string, ComfyInputConfig>> = {} private static defaultInputConfigs: Record<string, Record<string, ComfyInputConfig>> = {}

View File

@@ -1,8 +1,17 @@
import { LiteGraph, type ITextWidget, type SlotLayout, type INumberWidget } from "@litegraph-ts/core"; import { LiteGraph, type ITextWidget, type SlotLayout, type INumberWidget } from "@litegraph-ts/core";
import ComfyGraphNode from "./ComfyGraphNode"; import ComfyGraphNode, { type ComfyGraphNodeProperties } from "./ComfyGraphNode";
import { comfyFileToAnnotatedFilepath, type ComfyBoxImageMetadata } from "$lib/utils"; import { comfyFileToAnnotatedFilepath, type ComfyBoxImageMetadata } from "$lib/utils";
export interface ComfyPickImageProperties extends ComfyGraphNodeProperties {
imageTagFilter: string
}
export default class ComfyPickImageNode extends ComfyGraphNode { export default class ComfyPickImageNode extends ComfyGraphNode {
override properties: ComfyPickImageProperties = {
tags: [],
imageTagFilter: ""
}
static slotLayout: SlotLayout = { static slotLayout: SlotLayout = {
inputs: [ inputs: [
{ name: "images", type: "COMFYBOX_IMAGES,COMFYBOX_IMAGE" }, { name: "images", type: "COMFYBOX_IMAGES,COMFYBOX_IMAGE" },
@@ -13,57 +22,87 @@ export default class ComfyPickImageNode extends ComfyGraphNode {
{ name: "filename", type: "string" }, { name: "filename", type: "string" },
{ name: "width", type: "number" }, { name: "width", type: "number" },
{ name: "height", type: "number" }, { name: "height", type: "number" },
{ name: "children", type: "COMFYBOX_IMAGES" },
] ]
} }
tagFilterWidget: ITextWidget;
filepathWidget: ITextWidget; filepathWidget: ITextWidget;
folderWidget: ITextWidget; folderWidget: ITextWidget;
widthWidget: INumberWidget; widthWidget: INumberWidget;
heightWidget: INumberWidget; heightWidget: INumberWidget;
tagsWidget: ITextWidget;
childrenWidget: INumberWidget;
constructor(title?: string) { constructor(title?: string) {
super(title) super(title)
this.tagFilterWidget = this.addWidget("text", "Tag Filter", this.properties.imageTagFilter, "imageTagFilter")
this.filepathWidget = this.addWidget("text", "File", "") this.filepathWidget = this.addWidget("text", "File", "")
this.filepathWidget.disabled = true;
this.folderWidget = this.addWidget("text", "Folder", "") this.folderWidget = this.addWidget("text", "Folder", "")
this.folderWidget.disabled = true;
this.widthWidget = this.addWidget("number", "Width", 0) this.widthWidget = this.addWidget("number", "Width", 0)
this.widthWidget.disabled = true;
this.heightWidget = this.addWidget("number", "Height", 0) this.heightWidget = this.addWidget("number", "Height", 0)
for (const widget of this.widgets) this.heightWidget.disabled = true;
widget.disabled = true; this.tagsWidget = this.addWidget("text", "Tags", "")
this.tagsWidget.disabled = true;
this.childrenWidget = this.addWidget("number", "# of Children", 0)
this.childrenWidget.disabled = true;
} }
_value: ComfyBoxImageMetadata[] | null = null; _value: ComfyBoxImageMetadata[] | null = null;
_image: ComfyBoxImageMetadata | null = null; _image: ComfyBoxImageMetadata | null = null;
_path: string | null = null; _path: string | null = null;
_index: number = 0; _index: number | null = null;
private setValue(value: ComfyBoxImageMetadata[] | ComfyBoxImageMetadata | null, index: number) { private setValue(value: ComfyBoxImageMetadata[] | ComfyBoxImageMetadata | null, index: number) {
if (value != null && !Array.isArray(value)) { if (value != null && !Array.isArray(value)) {
value = [value] value = [value]
index = 0; index = 0;
} }
const changed = this._value != value || this._index != index;
this._value = value as ComfyBoxImageMetadata[]; this._value = value as ComfyBoxImageMetadata[];
this._index = index; this._index = index;
let image: ComfyBoxImageMetadata | null = null;
if (value && this._index != null && value[this._index] != null) {
image = value[this._index];
}
const changed = this._value != value || this._index != index || this._image != image;
if (changed) { if (changed) {
if (value && value[this._index] != null) { if (image) {
this._image = value[this._index] this._image = image
this._image.children ||= []
this._image.tags ||= []
this._path = comfyFileToAnnotatedFilepath(this._image.comfyUIFile); this._path = comfyFileToAnnotatedFilepath(this._image.comfyUIFile);
this.filepathWidget.value = this._image.comfyUIFile.filename this.filepathWidget.value = this._image.comfyUIFile.filename
this.folderWidget.value = this._image.comfyUIFile.type this.folderWidget.value = this._image.comfyUIFile.type
this.childrenWidget.value = this._image.children.length
this.tagsWidget.value = this._image.tags.join(", ")
} }
else { else {
this._image = null; this._image = null;
this._path = null; this._path = null;
this.filepathWidget.value = "(None)" this.filepathWidget.value = "(None)"
this.folderWidget.value = "" this.folderWidget.value = ""
this.childrenWidget.value = 0
this.tagsWidget.value = ""
} }
console.log("SET", value, this._image, this._path)
console.log("SET", value, this._image, this._path, this.properties.imageTagFilter)
} }
} }
override onExecute() { override onExecute() {
const data = this.getInputData(0) const data = this.getInputData(0)
const index = this.getInputData(1) || 0 let index = this.getInputData(1);
if (this.properties.imageTagFilter != "" && Array.isArray(data))
index = data.findIndex(i => i.tags?.includes(this.properties.imageTagFilter))
else if (index == null)
index = 0;
this.setValue(data, index); this.setValue(data, index);
if (this._image == null) { if (this._image == null) {
@@ -71,6 +110,7 @@ export default class ComfyPickImageNode extends ComfyGraphNode {
this.setOutputData(1, null) this.setOutputData(1, null)
this.setOutputData(2, 0) this.setOutputData(2, 0)
this.setOutputData(3, 0) this.setOutputData(3, 0)
this.setOutputData(4, null)
this.widthWidget.value = 0 this.widthWidget.value = 0
this.heightWidget.value = 0 this.heightWidget.value = 0
@@ -80,6 +120,7 @@ export default class ComfyPickImageNode extends ComfyGraphNode {
this.setOutputData(1, this._path); this.setOutputData(1, this._path);
this.setOutputData(2, this._image.width); this.setOutputData(2, this._image.width);
this.setOutputData(3, this._image.height); this.setOutputData(3, this._image.height);
this.setOutputData(4, this._image.children);
// XXX: image size doesn't load until the <img> element is ready on // XXX: image size doesn't load until the <img> element is ready on
// the page so this can come after several frames' worth of // the page so this can come after several frames' worth of

View File

@@ -41,6 +41,7 @@ export default class ComfyComboNode extends ComfyWidgetNode<string> {
firstLoad: Writable<boolean>; firstLoad: Writable<boolean>;
lightUp: Writable<boolean>; lightUp: Writable<boolean>;
valuesForCombo: Writable<any[]>; // Changed when the combo box has values. valuesForCombo: Writable<any[]>; // Changed when the combo box has values.
maxLabelWidthChars: number = 0;
constructor(name?: string) { constructor(name?: string) {
super(name, "A") super(name, "A")
@@ -77,13 +78,17 @@ export default class ComfyComboNode extends ComfyWidgetNode<string> {
else else
formatter = (value: any) => `${value}`; formatter = (value: any) => `${value}`;
this.maxLabelWidthChars = 0;
let valuesForCombo = [] let valuesForCombo = []
try { try {
valuesForCombo = this.properties.values.map((value, index) => { valuesForCombo = this.properties.values.map((value, index) => {
const label = formatter(value);
this.maxLabelWidthChars = Math.max(this.maxLabelWidthChars, label.length)
return { return {
value, value,
label: formatter(value), label,
index index
} }
}) })
@@ -91,9 +96,11 @@ export default class ComfyComboNode extends ComfyWidgetNode<string> {
catch (err) { catch (err) {
console.error("Failed formatting!", err) console.error("Failed formatting!", err)
valuesForCombo = this.properties.values.map((value, index) => { valuesForCombo = this.properties.values.map((value, index) => {
const label = `${value}`
this.maxLabelWidthChars = Math.max(this.maxLabelWidthChars, label.length)
return { return {
value, value,
label: `${value}`, label,
index index
} }
}) })

View File

@@ -6,14 +6,17 @@ import ImageUploadWidget from "$lib/widgets/ImageUploadWidget.svelte";
import type { ComfyWidgetProperties } from "./ComfyWidgetNode"; import type { ComfyWidgetProperties } from "./ComfyWidgetNode";
import ComfyWidgetNode from "./ComfyWidgetNode"; import ComfyWidgetNode from "./ComfyWidgetNode";
import { get, writable, type Writable } from "svelte/store"; import { get, writable, type Writable } from "svelte/store";
import { type LineGroup } from "$lib/components/MaskCanvas.svelte"
export interface ComfyImageUploadNodeProperties extends ComfyWidgetProperties { export interface ComfyImageUploadNodeProperties extends ComfyWidgetProperties {
maskCount: number
} }
export default class ComfyImageUploadNode extends ComfyWidgetNode<ComfyBoxImageMetadata[]> { export default class ComfyImageUploadNode extends ComfyWidgetNode<ComfyBoxImageMetadata[]> {
properties: ComfyImageUploadNodeProperties = { properties: ComfyImageUploadNodeProperties = {
defaultValue: [], defaultValue: [],
tags: [], tags: [],
maskCount: 0
} }
static slotLayout: SlotLayout = { static slotLayout: SlotLayout = {
@@ -39,13 +42,21 @@ export default class ComfyImageUploadNode extends ComfyWidgetNode<ComfyBoxImageM
super(name, []) super(name, [])
} }
override onExecute() { override onExecute(param: any, options: object) {
// TODO better way of getting image size? // TODO better way of getting image size?
const value = get(this.value) const value = get(this.value)
if (value && value.length > 0) { if (value && value.length > 0) {
value[0].width = get(this.imgWidth) value[0].width = get(this.imgWidth)
value[0].height = get(this.imgHeight) value[0].height = get(this.imgHeight)
// NOTE: assumes masks will have the same image size as the parent image!
for (const child of value[0].children) {
child.width = get(this.imgWidth)
child.height = get(this.imgHeight)
}
} }
super.onExecute(param, options);
} }
override parseValue(value: any): ComfyBoxImageMetadata[] { override parseValue(value: any): ComfyBoxImageMetadata[] {

View File

@@ -0,0 +1,200 @@
import { LinkRenderMode } from "@litegraph-ts/core";
/*
* Supported config option types.
*/
type ConfigDefType = "boolean" | "number" | "string" | "string[]" | "enum";
// A simple parameter description interface
export interface ConfigDef<IdType extends string, TypeType extends ConfigDefType, ValueType, OptionsType = any> {
// This generic `IdType` is what makes the "array of keys and values to new
// interface definition" thing work
name: IdType;
type: TypeType,
description?: string,
category: string,
defaultValue: ValueType,
options: OptionsType,
}
export type ConfigDefAny = ConfigDef<string, any, any>
export type ConfigDefBoolean<IdType extends string> = ConfigDef<IdType, "boolean", boolean>;
export type NumberOptions = {
min?: number,
max?: number,
step: number
}
export type ConfigDefNumber<IdType extends string> = ConfigDef<IdType, "number", number, NumberOptions>;
export type ConfigDefString<IdType extends string> = ConfigDef<IdType, "string", string>;
export type ConfigDefStringArray<IdType extends string> = ConfigDef<IdType, "string[]", string[]>;
export interface EnumValue<T> {
label: string,
value: T
}
export interface EnumOptions<T> {
values: EnumValue<T>[]
}
export type ConfigDefEnum<IdType extends string, T> = ConfigDef<IdType, "enum", T, EnumOptions<T>>;
export function validateConfigOption(def: ConfigDefAny, v: any): boolean {
switch (def.type) {
case "boolean":
return typeof v === "boolean";
case "number":
return typeof v === "number";
case "string":
return typeof v === "string";
case "string[]":
return Array.isArray(v) && v.every(vs => typeof vs === "string");
case "enum":
return Boolean(def.options.values.find((o: EnumValue<any>) => o.value === v));
}
return false;
}
// Configuration parameters ------------------------------------
const defComfyUIHostname: ConfigDefString<"comfyUIHostname"> = {
name: "comfyUIHostname",
type: "string",
defaultValue: "localhost",
category: "backend",
description: "Backend domain for ComfyUI",
options: {}
};
const defComfyUIPort: ConfigDefNumber<"comfyUIPort"> = {
name: "comfyUIPort",
type: "number",
defaultValue: 8188,
category: "backend",
description: "Backend port for ComfyUI",
options: {
min: 1,
max: 65535,
step: 1
}
};
const defAlwaysStripUserState: ConfigDefBoolean<"alwaysStripUserState"> = {
name: "alwaysStripUserState",
type: "boolean",
defaultValue: false,
category: "behavior",
description: "Strip user state even if saving to local storage",
options: {}
};
const defPromptForWorkflowName: ConfigDefBoolean<"promptForWorkflowName"> = {
name: "promptForWorkflowName",
type: "boolean",
defaultValue: false,
category: "behavior",
description: "When saving, always prompt for a name to save the workflow as",
options: {}
};
const defConfirmWhenUnloadingUnsavedChanges: ConfigDefBoolean<"confirmWhenUnloadingUnsavedChanges"> = {
name: "confirmWhenUnloadingUnsavedChanges",
type: "boolean",
defaultValue: true,
category: "behavior",
description: "When closing the tab, open the confirmation window if there's unsaved changes",
options: {}
};
const defCacheBuiltInResources: ConfigDefBoolean<"cacheBuiltInResources"> = {
name: "cacheBuiltInResources",
type: "boolean",
defaultValue: true,
category: "behavior",
description: "Cache loading of built-in resources to save network use",
options: {}
};
const defBuiltInTemplates: ConfigDefStringArray<"builtInTemplates"> = {
name: "builtInTemplates",
type: "string[]",
defaultValue: ["ControlNet", "LoRA x5", "Model Loader", "Positive_Negative", "Seed Randomizer"],
category: "templates",
description: "Basenames of templates that can be loaded from public/templates. Saves LocalStorage space.",
options: {}
};
// const defLinkDisplayType: ConfigDefEnum<"linkDisplayType", LinkRenderMode> = {
// name: "linkDisplayType",
// type: "enum",
// defaultValue: LinkRenderMode.SPLINE_LINK,
// category: "graph",
// description: "How to display links in the graph",
// options: {
// values: [
// {
// value: LinkRenderMode.STRAIGHT_LINK,
// label: "Straight"
// },
// {
// value: LinkRenderMode.LINEAR_LINK,
// label: "Linear"
// },
// {
// value: LinkRenderMode.SPLINE_LINK,
// label: "Spline"
// }
// ]
// },
// };
// Configuration exports ------------------------------------
export const CONFIG_DEFS = [
defComfyUIHostname,
defComfyUIPort,
defAlwaysStripUserState,
defPromptForWorkflowName,
defConfirmWhenUnloadingUnsavedChanges,
defCacheBuiltInResources,
defBuiltInTemplates,
// defLinkDisplayType
] as const;
export const CONFIG_DEFS_BY_NAME: Record<string, ConfigDefAny>
= CONFIG_DEFS.reduce((dict, def) => {
if (def.name in dict)
throw new Error(`Duplicate named config definition: ${def.name}`)
dict[def.name] = def;
return dict
}, {})
export const CONFIG_DEFS_BY_CATEGORY: Record<string, ConfigDefAny[]>
= CONFIG_DEFS.reduce((dict, def) => {
dict[def.category] ||= []
dict[def.category].push(def)
return dict
}, {})
export const CONFIG_CATEGORIES: string[]
= CONFIG_DEFS.reduce((arr, def) => {
if (!arr.includes(def.category))
arr.push(def.category)
return arr
}, [])
type Config<T extends ReadonlyArray<Readonly<ConfigDef<string, ConfigDefType, any>>>> = {
[K in T[number]["name"]]: Extract<T[number], { name: K }>["defaultValue"]
} extends infer O
? { [P in keyof O]: O[P] }
: never;
export type ConfigState = Config<typeof CONFIG_DEFS>
const pairs: [string, any][] = CONFIG_DEFS.map(item => { return [item.name, structuredClone(item.defaultValue)] })
export const defaultConfig: ConfigState = pairs.reduce((dict, v) => { dict[v[0]] = v[1]; return dict; }, {}) as any;

View File

@@ -1,54 +1,122 @@
import { debounce } from '$lib/utils'; import { debounce } from '$lib/utils';
import { toHashMap } from '@litegraph-ts/core';
import { get, writable } from 'svelte/store'; import { get, writable } from 'svelte/store';
import type { Writable } from 'svelte/store'; import type { Writable } from 'svelte/store';
import { defaultConfig, type ConfigState, type ConfigDefAny, CONFIG_DEFS_BY_NAME, validateConfigOption } from './configDefs';
export type ConfigState = {
/** Backend domain for ComfyUI */
comfyUIHostname: string,
/** Backend port for ComfyUI */
comfyUIPort: number,
/** Strip user state even if saving to local storage */
alwaysStripUserState: boolean,
/** When saving, always prompt for a name to save the workflow as */
promptForWorkflowName: boolean,
/** When closing the tab, open the confirmation window if there's unsaved changes */
confirmWhenUnloadingUnsavedChanges: boolean,
/** Basenames of templates that can be loaded from public/templates. Saves LocalStorage space. */
builtInTemplates: string[],
/** Cache loading of built-in resources to save network use */
cacheBuiltInResources: boolean
}
type ConfigStateOps = { type ConfigStateOps = {
getBackendURL: () => string getBackendURL: () => string,
load: (data: any, runOnChanged?: boolean) => ConfigState
loadDefault: (runOnChanged?: boolean) => ConfigState
setConfigOption: (def: ConfigDefAny, v: any, runOnChanged: boolean) => boolean
validateConfigOption: (def: ConfigDefAny, v: any) => boolean
onChange: <K extends keyof ConfigState>(optionName: K, callback: ConfigOnChangeCallback<ConfigState[K]>) => void
runOnChangedEvents: () => void,
} }
export type WritableConfigStateStore = Writable<ConfigState> & ConfigStateOps; export type WritableConfigStateStore = Writable<ConfigState> & ConfigStateOps;
const store: Writable<ConfigState> = writable( const store: Writable<ConfigState> = writable({ ...defaultConfig })
{ const callbacks: Record<string, ConfigOnChangeCallback<any>[]> = {}
comfyUIHostname: "localhost", let changedOptions: Partial<Record<keyof ConfigState, [any, any]>> = {}
comfyUIPort: 8188,
alwaysStripUserState: false,
promptForWorkflowName: false,
confirmWhenUnloadingUnsavedChanges: true,
builtInTemplates: [],
cacheBuiltInResources: true,
})
function getBackendURL(): string { function getBackendURL(): string {
const state = get(store); const state = get(store);
return `${window.location.protocol}//${state.comfyUIHostname}:${state.comfyUIPort}` return `${window.location.protocol}//${state.comfyUIHostname}:${state.comfyUIPort}`
} }
function setConfigOption(def: ConfigDefAny, v: any, runOnChanged: boolean): boolean {
let valid = false;
store.update(state => {
const oldValue = state[def.name]
valid = validateConfigOption(def, v);
if (!valid) {
console.warn(`[configState] Invalid value for option ${def.name} (${v}), setting to default (${def.defaultValue})`);
state[def.name] = structuredClone(def.defaultValue);
}
else {
state[def.name] = v
}
const changed = oldValue != state[def.name];
if (changed) {
if (runOnChanged) {
if (callbacks[def.name]) {
for (const callback of callbacks[def.name]) {
callback(state[def.name], oldValue)
}
}
}
else {
if (changedOptions[def.name] == null) {
changedOptions[def.name] = [oldValue, state[def.name]];
}
else {
changedOptions[def.name][1] = state[def.name]
}
}
}
return state;
})
return valid;
}
function load(data: any, runOnChanged: boolean = false): ConfigState {
changedOptions = {}
store.set({ ...defaultConfig })
if (data != null && typeof data === "object") {
for (const [k, v] of Object.entries(data)) {
const def = CONFIG_DEFS_BY_NAME[k]
if (def == null) {
delete data[k]
continue;
}
setConfigOption(def, v, runOnChanged);
}
}
return get(store);
}
function loadDefault(runOnChanged: boolean = false) {
return load(null, runOnChanged);
}
export type ConfigOnChangeCallback<V> = (value: V, oldValue?: V) => void;
function onChange<K extends keyof ConfigState>(optionName: K, callback: ConfigOnChangeCallback<ConfigState[K]>) {
callbacks[optionName] ||= []
callbacks[optionName].push(callback)
}
function runOnChangedEvents() {
console.debug("Running changed events for config...")
for (const [optionName, [oldValue, newValue]] of Object.entries(changedOptions)) {
const def = CONFIG_DEFS_BY_NAME[optionName]
if (callbacks[optionName]) {
console.debug("Running callback!", optionName, oldValue, newValue)
for (const callback of callbacks[def.name]) {
callback(newValue, oldValue)
}
}
}
changedOptions = {}
}
const configStateStore: WritableConfigStateStore = const configStateStore: WritableConfigStateStore =
{ {
...store, ...store,
getBackendURL getBackendURL,
validateConfigOption,
setConfigOption,
load,
loadDefault,
onChange,
runOnChangedEvents
} }
export default configStateStore; export default configStateStore;

View File

@@ -11,6 +11,7 @@ export type InterfaceState = {
indicatorValue: any, indicatorValue: any,
graphTransitioning: boolean graphTransitioning: boolean
isJumpingToNode: boolean
} }
type InterfaceStateOps = { type InterfaceStateOps = {
@@ -25,7 +26,8 @@ const store: Writable<InterfaceState> = writable(
showIndicator: false, showIndicator: false,
indicatorValue: null, indicatorValue: null,
graphTransitioning: false graphTransitioning: false,
isJumpingToNode: false,
}) })
const debounceDrag = debounce(() => { store.update(s => { s.showIndicator = false; return s }) }, 1000) const debounceDrag = debounce(() => { store.update(s => { s.showIndicator = false; return s }) }, 1000)

View File

@@ -616,6 +616,19 @@ const ALL_ATTRIBUTES: AttributesSpecList = [
defaultValue: true defaultValue: true
}, },
// ImageUpload
{
name: "maskCount",
type: "number",
location: "nodeProps",
editable: true,
validNodeTypes: ["ui/image_upload"],
defaultValue: 0,
min: 0,
max: 8,
step: 1
},
// Radio // Radio
{ {
name: "defaultValue", name: "defaultValue",
@@ -677,7 +690,7 @@ const ALL_ATTRIBUTES: AttributesSpecList = [
} }
] ]
} }
]; ] as const;
// This is needed so the specs can be iterated with svelte's keyed #each. // This is needed so the specs can be iterated with svelte's keyed #each.
let i = 0; let i = 0;
@@ -799,8 +812,8 @@ type LayoutStateOps = {
moveItem: (target: IDragItem, to: ContainerLayout, index?: number) => void, moveItem: (target: IDragItem, to: ContainerLayout, index?: number) => void,
groupItems: (dragItemIDs: DragItemID[], attrs?: Partial<Attributes>) => ContainerLayout, groupItems: (dragItemIDs: DragItemID[], attrs?: Partial<Attributes>) => ContainerLayout,
ungroup: (container: ContainerLayout) => void, ungroup: (container: ContainerLayout) => void,
findLayoutEntryForNode: (nodeId: ComfyNodeID) => DragItemEntry | null, findLayoutEntryForNode: (nodeId: NodeID) => DragItemEntry | null,
findLayoutForNode: (nodeId: ComfyNodeID) => IDragItem | null, findLayoutForNode: (nodeId: NodeID) => IDragItem | null,
iterateBreadthFirst: (id?: DragItemID | null) => Iterable<DragItemEntry>, iterateBreadthFirst: (id?: DragItemID | null) => Iterable<DragItemEntry>,
serialize: () => SerializedLayoutState, serialize: () => SerializedLayoutState,
serializeAtRoot: (rootID: DragItemID) => SerializedLayoutState, serializeAtRoot: (rootID: DragItemID) => SerializedLayoutState,
@@ -1203,7 +1216,7 @@ function createRaw(workflow: ComfyBoxWorkflow | null = null): WritableLayoutStat
store.set(state) store.set(state)
} }
function findLayoutEntryForNode(nodeId: ComfyNodeID): DragItemEntry | null { function findLayoutEntryForNode(nodeId: NodeID): DragItemEntry | null {
const state = get(store) const state = get(store)
const found = Object.entries(state.allItems).find(pair => const found = Object.entries(state.allItems).find(pair =>
pair[1].dragItem.type === "widget" pair[1].dragItem.type === "widget"
@@ -1213,7 +1226,7 @@ function createRaw(workflow: ComfyBoxWorkflow | null = null): WritableLayoutStat
return null; return null;
} }
function findLayoutForNode(nodeId: ComfyNodeID): WidgetLayout | null { function findLayoutForNode(nodeId: NodeID): WidgetLayout | null {
const found = findLayoutEntryForNode(nodeId); const found = findLayoutEntryForNode(nodeId);
if (!found) if (!found)
return null; return null;
@@ -1498,16 +1511,12 @@ function getLayoutByDragItemID(dragItemID: DragItemID): WritableLayoutStateStore
return Object.values(get(layoutStates).all).find(l => get(l).allItems[dragItemID] != null) return Object.values(get(layoutStates).all).find(l => get(l).allItems[dragItemID] != null)
} }
function getDragItemByNode(node: LGraphNode): WidgetLayout | null { function getDragItemByNode(node: LGraphNode): IDragItem | null {
const layout = getLayoutByNode(node); const layout = getLayoutByNode(node);
if (layout == null) if (layout == null)
return null; return null;
const entry = get(layout).allItemsByNode[node.id] return layout.findLayoutForNode(node.id);
if (entry && entry.dragItem.type === "widget")
return entry.dragItem as WidgetLayout;
return null;
} }
export type LayoutStateStores = { export type LayoutStateStores = {
@@ -1530,7 +1539,7 @@ export type LayoutStateStoresOps = {
getLayoutByGraph: (graph: LGraph) => WritableLayoutStateStore | null, getLayoutByGraph: (graph: LGraph) => WritableLayoutStateStore | null,
getLayoutByNode: (node: LGraphNode) => WritableLayoutStateStore | null, getLayoutByNode: (node: LGraphNode) => WritableLayoutStateStore | null,
getLayoutByDragItemID: (dragItemID: DragItemID) => WritableLayoutStateStore | null, getLayoutByDragItemID: (dragItemID: DragItemID) => WritableLayoutStateStore | null,
getDragItemByNode: (node: LGraphNode) => WidgetLayout | null, getDragItemByNode: (node: LGraphNode) => IDragItem | null,
} }
export type WritableLayoutStateStores = Writable<LayoutStateStores> & LayoutStateStoresOps; export type WritableLayoutStateStores = Writable<LayoutStateStores> & LayoutStateStoresOps;

View File

@@ -404,7 +404,7 @@ function setActiveWorkflow(canvas: ComfyGraphCanvas, index: number | WorkflowIns
const workflow = state.openedWorkflows[index] const workflow = state.openedWorkflows[index]
if (workflow.id === state.activeWorkflowID) if (workflow.id === state.activeWorkflowID)
return; return state.activeWorkflow;
if (state.activeWorkflow != null) if (state.activeWorkflow != null)
state.activeWorkflow.stop("app") state.activeWorkflow.stop("app")

View File

@@ -75,6 +75,13 @@ export function download(filename: string, text: string, type: string = "text/pl
}, 0); }, 0);
} }
export function downloadCanvas(canvas: HTMLCanvasElement, filename: string, type: string = "image/png") {
var link = document.createElement('a');
link.download = filename;
link.href = canvas.toDataURL(type);
link.click();
}
export const MAX_LOCAL_STORAGE_MB = 5; export const MAX_LOCAL_STORAGE_MB = 5;
export function getLocalStorageUsedMB(): number { export function getLocalStorageUsedMB(): number {
@@ -434,6 +441,8 @@ export type ComfyBoxImageMetadata = {
width?: number, width?: number,
/* Image height. */ /* Image height. */
height?: number, height?: number,
/* Child images associated with this image, like masks. */
children: ComfyBoxImageMetadata[]
} }
export function isComfyBoxImageMetadata(value: any): value is ComfyBoxImageMetadata { export function isComfyBoxImageMetadata(value: any): value is ComfyBoxImageMetadata {
@@ -458,6 +467,7 @@ export function filenameToComfyBoxMetadata(filename: string, type: ComfyUploadIm
}, },
name: "Filename", name: "Filename",
tags: [], tags: [],
children: []
} }
} }
@@ -467,6 +477,7 @@ export function comfyFileToComfyBoxMetadata(comfyUIFile: ComfyImageLocation): Co
comfyUIFile, comfyUIFile,
name: "File", name: "File",
tags: [], tags: [],
children: []
} }
} }
@@ -628,3 +639,70 @@ export function playSound(sound: string) {
const audio = new Audio(url); const audio = new Audio(url);
audio.play(); audio.play();
} }
export interface ComfyBatchUploadResult {
error?: string;
files: Array<ComfyImageLocation>;
}
export type ComfyBatchBlob = {
blob: Blob,
filename: string,
overwrite?: boolean
}
export async function batchUploadFilesToComfyUI(files: Array<File>): Promise<ComfyBatchUploadResult> {
const blobs = files.map(f => { return { blob: f, filename: f.name } })
return batchUploadBlobsToComfyUI(blobs)
}
export async function batchUploadBlobsToComfyUI(blobs: ComfyBatchBlob[]): Promise<ComfyBatchUploadResult> {
const url = configState.getBackendURL();
const requests = blobs.map(async (blob) => {
const formData = new FormData();
formData.append("image", blob.blob, blob.filename);
if (blob.overwrite) {
formData.append("overwrite", "true")
}
return fetch(new Request(url + "/upload/image", {
body: formData,
method: 'POST'
}))
.then(r => r.json())
.catch(error => error);
});
return Promise.all(requests)
.then((results) => {
const errors = []
const files = []
for (const r of results) {
if (r instanceof Error) {
errors.push(r.toString())
}
else {
// bare filename of image
const resp = r as ComfyUploadImageAPIResponse;
files.push({
filename: resp.name,
subfolder: "",
type: "input"
})
}
}
let error = null;
if (errors && errors.length > 0)
error = "Upload error(s):\n" + errors.join("\n");
return { error, files }
})
}
export function canvasToBlob(canvas: HTMLCanvasElement): Promise<Blob> {
return new Promise(function(resolve) {
canvas.toBlob(resolve);
});
}

View File

@@ -129,10 +129,25 @@
}; };
} }
let title: ""
$: nodeValue && $nodeValue && (title = getTitle($nodeValue))
function getTitle(value?: string) {
if (value == null) {
if (!nodeValue)
return ""
value = $nodeValue
}
if (value && value.length > 80)
return String(value)
return ""
}
</script> </script>
<div class="wrapper comfy-combo" class:mobile={isMobile} class:updated={$lightUp}> <div class="wrapper comfy-combo" class:mobile={isMobile} class:updated={$lightUp}>
<label> <label title={title}>
{#if widget.attrs.title !== ""} {#if widget.attrs.title !== ""}
<BlockTitle show_label={true}> <BlockTitle show_label={true}>
{widget.attrs.title} {widget.attrs.title}
@@ -158,7 +173,7 @@
on:select={(e) => handleSelect(e.detail.index)} on:select={(e) => handleSelect(e.detail.index)}
on:blur on:blur
on:filter={onFilter}> on:filter={onFilter}>
<div class="comfy-select-list" slot="list" let:filteredItems> <div class="comfy-select-list" slot="list" let:filteredItems style:--maxLabelWidth={node.maxLabelWidthChars || 100}>
{#if filteredItems.length > 0} {#if filteredItems.length > 0}
{@const itemSize = isMobile ? 50 : 25} {@const itemSize = isMobile ? 50 : 25}
{@const itemsToShow = isMobile ? 10 : 30} {@const itemsToShow = isMobile ? 10 : 30}
@@ -175,6 +190,7 @@
class:mobile={isMobile} class:mobile={isMobile}
let:index={i} let:index={i}
let:style let:style
title={getTitle(filteredItems[i].label)}
{style} {style}
class:active={activeIndex === filteredItems[i].index} class:active={activeIndex === filteredItems[i].index}
class:hover={hoverItemIndex === i} class:hover={hoverItemIndex === i}
@@ -274,7 +290,9 @@
} }
.comfy-select-list { .comfy-select-list {
width: 30rem; --maxLabelWidth: 100;
font-size: 14px;
width: min(calc((var(--maxLabelWidth) + 10) * 1ch), 50vw);
color: var(--item-color); color: var(--item-color);
> :global(.virtual-list-wrapper) { > :global(.virtual-list-wrapper) {

View File

@@ -3,46 +3,140 @@
import { Block } from "@gradio/atoms"; import { Block } from "@gradio/atoms";
import { TextBox } from "@gradio/form"; import { TextBox } from "@gradio/form";
import Row from "$lib/components/gradio/app/Row.svelte"; import Row from "$lib/components/gradio/app/Row.svelte";
import { get, writable, type Writable } from "svelte/store"; import { writable, type Writable } from "svelte/store";
import Modal from "$lib/components/Modal.svelte";
import { Button } from "@gradio/button"; import { Button } from "@gradio/button";
import { type Embed as Klecks } from "klecks"; import {
type ComfyBoxImageMetadata,
import "klecks/style/style.scss"; comfyFileToComfyBoxMetadata,
comfyBoxImageToComfyFile,
type ComfyImageLocation,
comfyBoxImageToComfyURL,
convertComfyOutputToComfyURL,
batchUploadBlobsToComfyUI,
canvasToBlob,
basename
} from "$lib/utils";
import ImageUpload from "$lib/components/ImageUpload.svelte"; import ImageUpload from "$lib/components/ImageUpload.svelte";
import { uploadImageToComfyUI, type ComfyBoxImageMetadata, comfyFileToComfyBoxMetadata, comfyBoxImageToComfyURL, comfyBoxImageToComfyFile, type ComfyUploadImageType, type ComfyImageLocation } from "$lib/utils";
import configState from "$lib/stores/configState";
import notify from "$lib/notify"; import notify from "$lib/notify";
import NumberInput from "$lib/components/NumberInput.svelte"; import { ImageViewer } from "$lib/ImageViewer";
import type { ComfyImageEditorNode } from "$lib/nodes/widgets"; import MaskCanvas, { type LineGroup, type MaskCanvasData } from "$lib/components/MaskCanvas.svelte";
import { ImageViewer } from "$lib/ImageViewer"; import type { ComfyImageUploadNode } from "$lib/nodes/widgets";
import { generateBlankCanvas, generateImageCanvas } from "./utils"; import { tick } from "svelte";
export let widget: WidgetLayout | null = null; export let widget: WidgetLayout | null = null;
export let isMobile: boolean = false; export let isMobile: boolean = false;
let node: ComfyImageEditorNode | null = null; let node: ComfyImageUploadNode | null = null;
let nodeValue: Writable<ComfyBoxImageMetadata[]> | null = null; let nodeValue: Writable<ComfyBoxImageMetadata[]> | null = null;
let attrsChanged: Writable<number> | null = null;
let imgWidth: Writable<number> = writable(0); let imgWidth: Writable<number> = writable(0);
let imgHeight: Writable<number> = writable(0); let imgHeight: Writable<number> = writable(0);
let maskCanvasComp: MaskCanvas | null = null;
let editMask: boolean = false;
$: widget && setNodeValue(widget); $: widget && setNodeValue(widget);
let canMask = false;
$: canMask = (node?.properties?.maskCount || 0) > 0;
$: if (!canMask) clearMask();
function setNodeValue(widget: WidgetLayout) { function setNodeValue(widget: WidgetLayout) {
if (widget) { if (widget) {
node = widget.node as ComfyImageEditorNode node = widget.node as ComfyImageUploadNode
nodeValue = node.value; nodeValue = node.value;
attrsChanged = widget.attrsChanged;
imgWidth = node.imgWidth imgWidth = node.imgWidth
imgHeight = node.imgHeight imgHeight = node.imgHeight
status = $nodeValue && $nodeValue.length > 0 ? "uploaded" : "empty" status = $nodeValue && $nodeValue.length > 0 ? "uploaded" : "empty"
} }
}; };
let hasImage = false;
$: hasImage = $nodeValue && $nodeValue.length > 0;
$: if (!hasImage) {
editMask = false;
}
const MASK_FILENAME: string = "ComfyBoxMask.png"
async function onMaskReleased(e: CustomEvent<MaskCanvasData>) {
const data = e.detail;
if (data.maskCanvas != null && data.hasMask) {
await saveMask(data.maskCanvas)
}
}
async function saveMask(maskCanvas: HTMLCanvasElement) {
if (!canMask) {
notify("Mask editing is disabled for this widget.", { type: "warning" })
return;
}
if (!maskCanvas) {
notify("No mask canvas!", { type: "warning" })
return
}
if (!$nodeValue || $nodeValue.length === 0) {
notify("No image uploaded to apply mask to.", { type: "warning" })
return
}
const hadNoMask = $nodeValue[0].children.findIndex(i => i.tags?.includes("mask")) === -1;
const existFilename = $nodeValue[0].comfyUIFile.filename
const filename = existFilename ? `${basename(existFilename)}_mask.png` : MASK_FILENAME
console.warn("[ImageUpload] UPLOAD MASK", filename)
await canvasToBlob(maskCanvas)
.then(blob => batchUploadBlobsToComfyUI([{
blob,
filename,
overwrite: true
}]))
.then(result => {
const meta = result.files.map(f => {
const m = comfyFileToComfyBoxMetadata(f)
m.tags = ["mask"]
m.width = maskCanvas.width;
m.height = maskCanvas.height;
return m;
});
if ($nodeValue.length > 0) {
// TODO support multiple images?
$nodeValue[0].children = meta;
if (hadNoMask) {
notify("Uploaded mask successfully!", { type: "success" })
}
}
else {
throw new Error("No image was uploaded yet.")
}
})
.catch(error => {
notify(`Failed to upload mask to ComfyUI: ${error}`, { type: "error", timeout: 10000 })
})
}
function clearMask() {
for (const image of $nodeValue) {
// TODO other child image types preserved here?
image.children = [];
}
if (maskCanvasComp) {
maskCanvasComp.clearStrokes();
}
}
async function toggleEditMask() {
editMask = !editMask;
await tick();
if (maskCanvasComp) {
maskCanvasComp.recenterImage();
}
}
let editorRoot: HTMLDivElement | null = null; let editorRoot: HTMLDivElement | null = null;
let showModal = false; let showModal = false;
let kl: Klecks | null = null;
function disposeEditor() { function disposeEditor() {
console.warn("[ImageEditorWidget] CLOSING", widget, $nodeValue) console.warn("[ImageEditorWidget] CLOSING", widget, $nodeValue)
@@ -53,100 +147,9 @@
} }
} }
kl = null;
showModal = false; showModal = false;
} }
const FILENAME: string = "ComfyUITemp.png";
const SUBFOLDER: string = "ComfyBox_Editor";
const DIRECTORY: ComfyUploadImageType = "input";
async function submitKlecksToComfyUI(onSuccess: () => void, onError: () => void) {
const blob = kl.getPNG();
status = "uploading"
await uploadImageToComfyUI(blob, FILENAME, DIRECTORY, SUBFOLDER)
.then((entry: ComfyImageLocation) => {
const meta: ComfyBoxImageMetadata = comfyFileToComfyBoxMetadata(entry);
$nodeValue = [meta] // TODO more than one image
status = "uploaded"
notify("Saved image to ComfyUI!", { type: "success" })
onSuccess();
})
.catch(err => {
notify(`Failed to upload image from editor: ${err}`, { type: "error", timeout: 10000 })
status = "error"
uploadError = err;
$nodeValue = []
onError();
})
}
let closeDialog = null;
async function saveAndClose() {
console.log(closeDialog, kl)
if (!closeDialog || !kl)
return;
submitKlecksToComfyUI(() => {}, () => {});
closeDialog()
}
let blankImageWidth = 512;
let blankImageHeight = 512;
let klecks: typeof import("klecks") | null = null;
async function openImageEditor() {
if (!editorRoot)
return;
showModal = true;
const url = configState.getBackendURL();
klecks ||= await import("klecks");
kl = new klecks.Embed({
embedUrl: url,
onSubmit: submitKlecksToComfyUI,
targetEl: editorRoot,
warnOnPageClose: false
});
console.warn("[ImageEditorWidget] OPENING", widget, $nodeValue)
let canvas = null;
let width = blankImageWidth;
let height = blankImageHeight;
if ($nodeValue && $nodeValue.length > 0) {
const comfyImage = $nodeValue[0];
const comfyURL = comfyBoxImageToComfyURL(comfyImage);
[canvas, width, height] = await generateImageCanvas(comfyURL);
}
else {
canvas = generateBlankCanvas(width, height);
}
kl.openProject({
width: width,
height: height,
layers: [{
name: 'Image',
opacity: 1,
mixModeStr: 'source-over',
image: canvas
}]
});
setTimeout(function () {
kl?.klApp?.out("yo");
}, 1000);
}
function openLightbox() { function openLightbox() {
if (!$nodeValue || $nodeValue.length === 0) if (!$nodeValue || $nodeValue.length === 0)
return; return;
@@ -189,9 +192,6 @@
notify(`Failed to upload image to ComfyUI: ${uploadError}`, { type: "error", timeout: 10000 }) notify(`Failed to upload image to ComfyUI: ${uploadError}`, { type: "error", timeout: 10000 })
} }
function onChange(e: CustomEvent<ComfyImageLocation[]>) {
}
let _value: ComfyImageLocation[] = [] let _value: ComfyImageLocation[] = []
$: if ($nodeValue) $: if ($nodeValue)
_value = $nodeValue.map(comfyBoxImageToComfyFile) _value = $nodeValue.map(comfyBoxImageToComfyFile)
@@ -199,6 +199,9 @@
_value = [] _value = []
$: canEdit = status === "empty" || status === "uploaded"; $: canEdit = status === "empty" || status === "uploaded";
function onChange(e: CustomEvent<ComfyImageLocation[]>) {
}
</script> </script>
<div class="wrapper comfy-image-editor"> <div class="wrapper comfy-image-editor">
@@ -219,64 +222,50 @@
/> />
{:else} {:else}
<div class="comfy-image-editor-panel"> <div class="comfy-image-editor-panel">
<ImageUpload value={_value} {#if _value && canMask}
bind:imgWidth={$imgWidth} {@const comfyURL = convertComfyOutputToComfyURL(_value[0])}
bind:imgHeight={$imgHeight} <div class="mask-canvas-wrapper" style:display={editMask ? "block" : "none"}>
fileCount={"single"} <MaskCanvas bind:this={maskCanvasComp} fileURL={comfyURL} on:release={onMaskReleased} on:loaded={onMaskReleased} />
elem_classes={[]}
style={""}
label={widget.attrs.title}
on:uploading={onUploading}
on:uploaded={onUploaded}
on:upload_error={onUploadError}
on:clear={onClear}
on:change={onChange}
on:image_clicked={openLightbox}
/>
<Modal bind:showModal closeOnClick={false} on:close={disposeEditor} bind:closeDialog>
<div>
<div id="klecks-loading-screen">
<span id="klecks-loading-screen-text"></span>
</div>
<div class="image-editor-root" bind:this={editorRoot} />
</div> </div>
<div slot="buttons"> {/if}
<Button variant="primary" on:click={saveAndClose}> <div style:display={(canMask && editMask) ? "none" : "block"}>
Save and Close <ImageUpload value={_value}
</Button> bind:imgWidth={$imgWidth}
<Button variant="secondary" on:click={closeDialog}> bind:imgHeight={$imgHeight}
Discard Edits fileCount={"single"}
</Button> elem_classes={[]}
</div> style={""}
</Modal> label={widget.attrs.title}
on:uploading={onUploading}
on:uploaded={onUploaded}
on:upload_error={onUploadError}
on:clear={onClear}
on:change={onChange}
on:image_clicked={openLightbox}
/>
</div>
<Block> <Block>
{#if !$nodeValue || $nodeValue.length === 0} {#if hasImage}
{@const maskCount = $nodeValue[0] ? $nodeValue[0].children.filter(f => f.tags?.includes("mask")).length : 0}
<Row> <Row>
<Row> {#if canMask}
<Button variant="secondary" disabled={!canEdit} on:click={openImageEditor}>
Create Image
</Button>
<div> <div>
<TextBox show_label={false} disabled={true} value="Status: {status}"/> {#if editMask}
<Button variant="secondary" on:click={() => { clearMask(); notify("Mask cleared."); }}>
Clear Mask
</Button>
{/if}
<Button disabled={!_value} on:click={toggleEditMask}>
{#if editMask}
Show Image
{:else}
Edit Mask
{/if}
</Button>
</div> </div>
{#if uploadError} {/if}
<div>
Upload error: {uploadError}
</div>
{/if}
</Row>
<Row>
<NumberInput label={"Width"} min={64} max={2048} step={64} bind:value={blankImageWidth} />
<NumberInput label={"Height"} min={64} max={2048} step={64} bind:value={blankImageHeight} />
</Row>
</Row>
{:else}
<Row>
<Button variant="secondary" disabled={!canEdit} on:click={openImageEditor}>
Edit Image
</Button>
<div> <div>
<TextBox label={""} show_label={false} disabled={true} lines={1} max_lines={1} value="Status: {status}"/> <TextBox label={""} show_label={false} disabled={true} lines={1} max_lines={1} value="Images: {$nodeValue.length}, masks: {maskCount}"/>
</div> </div>
{#if uploadError} {#if uploadError}
<div> <div>
@@ -291,25 +280,13 @@
</div> </div>
<style lang="scss"> <style lang="scss">
.image-editor-root {
width: 75vw;
height: 75vh;
overflow: hidden;
color: black;
:global(> .g-root) {
height: calc(100% - 59px);
}
}
.comfy-image-editor { .comfy-image-editor {
:global(> dialog) { :global(> dialog) {
overflow: hidden; overflow: hidden;
} }
} }
:global(.kl-popup) { .mask-canvas-wrapper {
z-index: 999999999999; height: calc(var(--size-96) * 1.5);
} }
</style> </style>

View File

@@ -92,33 +92,43 @@ body {
&.primary { &.primary {
background: var(--button-primary-background-fill); background: var(--button-primary-background-fill);
&:hover { &:hover:not(:disabled) {
background: var(--button-primary-background-fill-hover); background: var(--button-primary-background-fill-hover);
} }
} }
&.secondary { &.secondary {
background: var(--button-secondary-background-fill); background: var(--button-secondary-background-fill);
&:hover { &:hover:not(:disabled) {
background: var(--button-secondary-background-fill-hover); background: var(--button-secondary-background-fill-hover);
} }
} }
&.ternary { &.ternary {
background: var(--panel-background-fill); background: var(--panel-background-fill);
&:hover { &:hover:not(:disabled) {
background: var(--block-background-fill); background: var(--block-background-fill);
} }
&.selected {
background: var(--panel-background-fill);
}
} }
&:hover { &:hover:not(:disabled) {
filter: brightness(85%); filter: brightness(85%);
} }
&:active { &:active:not(:disabled) {
filter: brightness(50%) filter: brightness(50%)
} }
&.selected { &.selected {
filter: brightness(80%) color: var(--body-text-color);
filter: none;
}
&:disabled:not(.selected) {
background: var(--neutral-700);
color: var(--neutral-400);
opacity: 50%;
} }
} }

View File

@@ -0,0 +1,33 @@
import { get } from "svelte/store";
import configState, { type ConfigState } from "$lib/stores/configState"
import { expect } from 'vitest';
import UnitTest from "../UnitTest";
import { Watch } from "@litegraph-ts/nodes-basic";
export default class configStateTests extends UnitTest {
test__loadsDefaultsFromInvalid() {
const saved = "foo"
const config = configState.load(saved)
expect(config).toBeInstanceOf(Object)
expect(config.comfyUIHostname).toEqual("localhost")
}
test__loadsDefaultsFromBlank() {
const saved = {}
const config = configState.load(saved)
expect(config).toBeInstanceOf(Object)
expect(config.comfyUIHostname).toEqual("localhost")
}
test__loadsDefaultsFromInvalidValues() {
const saved = {
comfyUIHostname: 1234 as any
}
const config = configState.load(saved)
expect(config).toBeInstanceOf(Object)
expect(config.comfyUIHostname).toEqual("localhost")
}
}

View File

@@ -3,3 +3,4 @@ export { default as ComfyGraphTests } from "./ComfyGraphTests"
export { default as parseA1111Tests } from "./parseA1111Tests" export { default as parseA1111Tests } from "./parseA1111Tests"
export { default as convertA1111ToStdPromptTests } from "./convertA1111ToStdPromptTests" export { default as convertA1111ToStdPromptTests } from "./convertA1111ToStdPromptTests"
export { default as convertVanillaWorkflowTest } from "./convertVanillaWorkflowTests" export { default as convertVanillaWorkflowTest } from "./convertVanillaWorkflowTests"
export { default as configStateTests } from "./stores/configStateTests"