Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/lib/litegraph/src/types/widgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export type IWidget =
| ICompositorWidget
| IRangeWidget
| IVideoEditWidget
| IResolutionPreviewWidget
| IBoundingBoxesWidget
| IColorsWidget

Expand Down Expand Up @@ -424,6 +425,21 @@ export interface IVideoEditWidget extends IBaseWidget<
value: VideoEditValue
}

export interface IWidgetResolutionPreviewOptions extends IWidgetOptions {
ratio_widget?: string
megapixels_widget?: string
multiple_widget?: string
}

export interface IResolutionPreviewWidget extends IBaseWidget<
null,
'resolutionpreview',
IWidgetResolutionPreviewOptions
> {
type: 'resolutionpreview'
value: null
}

/**
* Valid widget types. TS cannot provide easily extensible type safety for this at present.
* Override linkedWidgets[]
Expand Down
1 change: 1 addition & 0 deletions src/locales/en/main.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"g": {
"shortcutSuffix": " ({shortcut})",
"megapixelsValue": "{count} MP",
"user": "User",
"you": "You",
"currentUser": "Current user",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import { createTestingPinia } from '@pinia/testing'
import { render, screen } from '@testing-library/vue'
import { setActivePinia } from 'pinia'
import type { Pinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'

const resolveNodeMock = vi.hoisted(() => vi.fn())
vi.mock('@/utils/litegraphUtil', () => ({ resolveNode: resolveNodeMock }))

import type { IWidgetResolutionPreviewOptions } from '@/lib/litegraph/src/types/widgets'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { toNodeId } from '@/types/nodeId'
import type { SimplifiedWidget } from '@/types/simplifiedWidget'
import { widgetId } from '@/types/widgetId'

import WidgetResolutionPreview from './WidgetResolutionPreview.vue'

const GRAPH_ID = 'test-graph'
const NODE_ID = toNodeId(1)

const i18n = createI18n({
legacy: false,
locale: 'en',
messages: {
en: {
g: { megapixelsValue: '{count} MP' }
}
}
})

let pinia: Pinia

beforeEach(() => {
pinia = createTestingPinia({ stubActions: false })
setActivePinia(pinia)
resolveNodeMock.mockReturnValue({
id: NODE_ID,
graph: { rootGraph: { id: GRAPH_ID } }
})
})

function registerSibling(name: string, type: string, value: unknown) {
useWidgetValueStore().registerWidget(widgetId(GRAPH_ID, NODE_ID, name), {
type,
value: value as never,
options: {}
})
}

function registerDefaultSiblings(
aspectRatio: string,
megapixels: number,
multiple: number
) {
registerSibling('aspect_ratio', 'combo', aspectRatio)
registerSibling('megapixels', 'number', megapixels)
registerSibling('multiple', 'number', multiple)
}

function renderPreview(options: IWidgetResolutionPreviewOptions = {}) {
const widget: SimplifiedWidget<null, IWidgetResolutionPreviewOptions> = {
name: 'preview',
type: 'resolutionpreview',
value: null,
options
}
return render(WidgetResolutionPreview, {
props: { widget, nodeId: NODE_ID },
global: { plugins: [pinia, i18n] }
})
}

function displayedValue(): string {
return screen.getByTestId('resolution-preview-value').textContent.trim()
}

describe('WidgetResolutionPreview', () => {
// Expected values generated from ResolutionSelector.execute in
// comfy_extras/nodes_resolution.py (Comfy-Org/ComfyUI#16013) — the
// backend contract tests in that repo pin the same formula.
it.for([
['1:1 (Square)', '1024 × 1024'],
['2:3 (Portrait Photo)', '840 × 1256'],
['3:2 (Photo)', '1256 × 840'],
['3:4 (Portrait Standard)', '888 × 1184'],
['4:3 (Standard)', '1184 × 888'],
['9:16 (Portrait Widescreen)', '768 × 1368'],
['16:9 (Widescreen)', '1368 × 768'],
['21:9 (Ultrawide)', '1568 × 672']
] as const)(
'matches the backend for %s at 1.0 MP ×8',
([label, expected]) => {
registerDefaultSiblings(label, 1.0, 8)
renderPreview()

expect(displayedValue()).toBe(expected)
}
)

it('matches the backend for a non-default multiple', () => {
registerDefaultSiblings('3:4 (Portrait Standard)', 2.0, 32)
renderPreview()

expect(displayedValue()).toBe('1248 × 1664')
})

it('rounds half-ties to even like Python round()', () => {
// scale is exactly 1028 here, so width/multiple is an exact 128.5 tie:
// Math.round would produce 1032, the backend produces 1024.
registerDefaultSiblings('1:1 (Square)', 1.0078277587890625, 8)
renderPreview()

expect(displayedValue()).toBe('1024 × 1024')
})

it('supports non-integer ratio labels', () => {
registerDefaultSiblings('1.85:1 (Cinema)', 1.0, 8)
renderPreview()

expect(displayedValue()).toBe('1392 × 752')
})

it('updates live when a sibling value changes in the store', async () => {
registerDefaultSiblings('1:1 (Square)', 1.0, 8)
renderPreview()
expect(displayedValue()).toBe('1024 × 1024')

useWidgetValueStore().setValue(
widgetId(GRAPH_ID, NODE_ID, 'aspect_ratio'),
'16:9 (Widescreen)'
)
await nextTick()

expect(displayedValue()).toBe('1368 × 768')
})

it('reads siblings through the configured widget names', () => {
registerSibling('ratio', 'combo', '16:9 (Widescreen)')
registerSibling('mp', 'number', 0.4)
registerSibling('resolution_steps', 'number', 32)
renderPreview({
ratio_widget: 'ratio',
megapixels_widget: 'mp',
multiple_widget: 'resolution_steps'
})

expect(displayedValue()).toBe('864 × 480')
})

it('renders the placeholder when siblings are not registered', () => {
renderPreview()

expect(screen.queryByTestId('resolution-preview-value')).toBeNull()
expect(screen.getByText('—')).toBeTruthy()
})

it('renders the placeholder instead of guessing a missing multiple', () => {
registerSibling('aspect_ratio', 'combo', '1:1 (Square)')
registerSibling('megapixels', 'number', 1.0)
renderPreview()

expect(screen.queryByTestId('resolution-preview-value')).toBeNull()
expect(screen.getByText('—')).toBeTruthy()
})

it.for([
{ desc: 'a malformed ratio label', ratio: 'Square', mp: 1.0, multiple: 8 },
{
desc: 'a zero-component ratio',
ratio: '0:1 (Degenerate)',
mp: 1.0,
multiple: 8
},
{
desc: 'non-positive megapixels',
ratio: '1:1 (Square)',
mp: 0,
multiple: 8
},
{
desc: 'a non-numeric megapixels value',
ratio: '1:1 (Square)',
mp: '1.0',
multiple: 8
},
{
desc: 'a non-positive multiple',
ratio: '1:1 (Square)',
mp: 1.0,
multiple: 0
}
])('renders the placeholder for $desc', ({ ratio, mp, multiple }) => {
registerSibling('aspect_ratio', 'combo', ratio)
registerSibling('megapixels', 'number', mp)
registerSibling('multiple', 'number', multiple)
renderPreview()

expect(screen.queryByTestId('resolution-preview-value')).toBeNull()
expect(screen.getByText('—')).toBeTruthy()
})

it('shows a preview once siblings become registered', async () => {
renderPreview()
expect(screen.queryByTestId('resolution-preview-value')).toBeNull()

registerDefaultSiblings('1:1 (Square)', 1.0, 8)
await nextTick()

expect(displayedValue()).toBe('1024 × 1024')
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<template>
<div
:class="
cn(
WidgetInputBaseClass,
'flex w-full items-center justify-center gap-2 px-2',
useWidgetHeight()
)
"
:data-widget-name="widget.name"
>
<template v-if="resolution">
<span class="text-xs" data-testid="resolution-preview-value">
{{ resolution.width }} × {{ resolution.height }}
</span>
<span class="text-xs text-muted-foreground">
{{ resolution.mpLabel }}
</span>
</template>
<span v-else class="text-xs text-muted-foreground"> — </span>
</div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

import type { IWidgetResolutionPreviewOptions } from '@/lib/litegraph/src/types/widgets'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import type { NodeId } from '@/types/nodeId'
import type { SimplifiedWidget } from '@/types/simplifiedWidget'
import { widgetId } from '@/types/widgetId'
import { useWidgetHeight } from '@/types/widgetTypes'
import { resolveNode } from '@/utils/litegraphUtil'
import { cn } from '@comfyorg/tailwind-utils'

import { WidgetInputBaseClass } from './layout'

const { widget, nodeId } = defineProps<{
widget: SimplifiedWidget<null, IWidgetResolutionPreviewOptions>
nodeId?: NodeId
}>()

const { t } = useI18n()
const widgetValueStore = useWidgetValueStore()

const hostNode = computed(() =>
nodeId === undefined ? undefined : resolveNode(nodeId)
)

function siblingValue(name: string): unknown {
const node = hostNode.value
const graphId = node?.graph?.rootGraph.id
if (!node || !graphId) return undefined
return widgetValueStore.getWidget(widgetId(graphId, node.id, name))?.value
}

// Python round() ties to even; Math.round ties up.
function roundHalfToEven(value: number): number {
const floor = Math.floor(value)
if (value - floor !== 0.5) return Math.round(value)
return floor % 2 === 0 ? floor : floor + 1
}

// Mirrors ResolutionSelector.execute in comfy_extras/nodes_resolution.py —
// keep the math in sync with the backend.
const resolution = computed(() => {
const ratioRaw = siblingValue(widget.options?.ratio_widget ?? 'aspect_ratio')
const mpRaw = siblingValue(widget.options?.megapixels_widget ?? 'megapixels')
const multipleRaw = siblingValue(
widget.options?.multiple_widget ?? 'multiple'
)

const match =
typeof ratioRaw === 'string'
? /^(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)/.exec(ratioRaw)
: null
const megapixels = typeof mpRaw === 'number' ? mpRaw : NaN
const multiple =
typeof multipleRaw === 'number' && multipleRaw > 0 ? multipleRaw : null
if (
!match ||
!Number.isFinite(megapixels) ||
megapixels <= 0 ||
multiple === null
) {
return null
}

const wRatio = Number(match[1])
const hRatio = Number(match[2])
if (!(wRatio > 0) || !(hRatio > 0)) return null
const scale = Math.sqrt((megapixels * 1024 * 1024) / (wRatio * hRatio))
const width = roundHalfToEven((wRatio * scale) / multiple) * multiple
const height = roundHalfToEven((hRatio * scale) / multiple) * multiple
if (!width || !height) return null

return {
width,
height,
mpLabel: t('g.megapixelsValue', {
count: ((width * height) / (1024 * 1024)).toFixed(2)
})
}
})
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
import type {
IResolutionPreviewWidget,
IWidgetResolutionPreviewOptions
} from '@/lib/litegraph/src/types/widgets'
import { isResolutionPreviewInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'

export const useResolutionPreviewWidget = (): ComfyWidgetConstructorV2 => {
return (
node: LGraphNode,
inputSpec: InputSpecV2
): IResolutionPreviewWidget => {
const spec = isResolutionPreviewInputSpec(inputSpec) ? inputSpec : undefined
const options: IWidgetResolutionPreviewOptions = {
serialize: false,
canvasOnly: false,
hideInPanel: true,
ratio_widget: spec?.ratio_widget,
megapixels_widget: spec?.megapixels_widget,
multiple_widget: spec?.multiple_widget
}
const rawWidget = node.addWidget(
'resolutionpreview',
inputSpec.name,
null,
() => {},
options
)
rawWidget.serialize = false

return rawWidget as IResolutionPreviewWidget
}
}
Loading
Loading