mirror of
https://github.com/Comfy-Org/ComfyUI_frontend.git
synced 2026-04-04 03:29:10 +00:00
Compare commits
2 Commits
fix/codera
...
fix/codera
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8db2739bc | ||
|
|
7cb07f9b2d |
78
src/composables/element/useDomValueBridge.test.ts
Normal file
78
src/composables/element/useDomValueBridge.test.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { nextTick } from 'vue'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { useDomValueBridge } from './useDomValueBridge'
|
||||
|
||||
function createInput(initialValue = ''): HTMLInputElement {
|
||||
const el = document.createElement('input')
|
||||
el.value = initialValue
|
||||
return el
|
||||
}
|
||||
|
||||
function createTextarea(initialValue = ''): HTMLTextAreaElement {
|
||||
const el = document.createElement('textarea')
|
||||
el.value = initialValue
|
||||
return el
|
||||
}
|
||||
|
||||
describe('useDomValueBridge', () => {
|
||||
it('initializes the ref with the current element value', () => {
|
||||
const el = createInput('hello')
|
||||
const bridged = useDomValueBridge(el)
|
||||
expect(bridged.value).toBe('hello')
|
||||
})
|
||||
|
||||
it('updates the ref when element.value is set programmatically', () => {
|
||||
const el = createInput('')
|
||||
const bridged = useDomValueBridge(el)
|
||||
|
||||
el.value = 'updated'
|
||||
expect(bridged.value).toBe('updated')
|
||||
})
|
||||
|
||||
it('updates the ref on user input events', () => {
|
||||
const el = createInput('')
|
||||
const bridged = useDomValueBridge(el)
|
||||
|
||||
// Simulate user typing by using the original descriptor to set value,
|
||||
// then dispatching an input event
|
||||
const proto = Object.getPrototypeOf(el)
|
||||
const desc = Object.getOwnPropertyDescriptor(proto, 'value')
|
||||
desc?.set?.call(el, 'typed')
|
||||
el.dispatchEvent(new Event('input'))
|
||||
|
||||
expect(bridged.value).toBe('typed')
|
||||
})
|
||||
|
||||
it('updates the DOM element when the ref is written to', async () => {
|
||||
const el = createInput('initial')
|
||||
const bridged = useDomValueBridge(el)
|
||||
|
||||
bridged.value = 'from-ref'
|
||||
await nextTick()
|
||||
|
||||
expect(el.value).toBe('from-ref')
|
||||
})
|
||||
|
||||
it('works with textarea elements', () => {
|
||||
const el = createTextarea('initial')
|
||||
const bridged = useDomValueBridge(el)
|
||||
|
||||
expect(bridged.value).toBe('initial')
|
||||
el.value = 'new text'
|
||||
expect(bridged.value).toBe('new text')
|
||||
})
|
||||
|
||||
it('reads element value through the intercepted getter', async () => {
|
||||
const el = createInput('start')
|
||||
const bridged = useDomValueBridge(el)
|
||||
|
||||
// The getter on element.value should still work
|
||||
expect(el.value).toBe('start')
|
||||
|
||||
bridged.value = 'changed'
|
||||
await nextTick()
|
||||
// The element getter should reflect the latest set
|
||||
expect(el.value).toBe('changed')
|
||||
})
|
||||
})
|
||||
79
src/composables/element/useDomValueBridge.ts
Normal file
79
src/composables/element/useDomValueBridge.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { ref, watch } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
type ValueElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
|
||||
|
||||
/**
|
||||
* Bridges a DOM element's `.value` property to a Vue reactive ref.
|
||||
*
|
||||
* This composable provides a clean, public API for extension authors to
|
||||
* synchronize DOM widget values with Vue reactivity (and by extension, the
|
||||
* `widgetValueStore`). It works by:
|
||||
*
|
||||
* 1. Intercepting programmatic `.value` writes via `Object.defineProperty`
|
||||
* 2. Listening for user-driven `input` events on the element
|
||||
* 3. Exposing a reactive `Ref<string>` that stays in sync with the DOM
|
||||
*
|
||||
* When the returned ref is written to, the DOM element's value is updated.
|
||||
* When the DOM element's value changes (programmatically or via user input),
|
||||
* the ref is updated.
|
||||
*
|
||||
* @param element - The DOM element to bridge (input, textarea, or select)
|
||||
* @returns A reactive ref that stays in sync with the element's value
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // In a custom widget's getValue/setValue:
|
||||
* const bridgedValue = useDomValueBridge(inputEl)
|
||||
* const widget = node.addDOMWidget(name, type, inputEl, {
|
||||
* getValue: () => bridgedValue.value,
|
||||
* setValue: (v) => { bridgedValue.value = v }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export function useDomValueBridge(element: ValueElement): Ref<string> {
|
||||
const bridgedValue = ref(element.value)
|
||||
|
||||
// Capture the original property descriptor so we can chain through it
|
||||
const proto = Object.getPrototypeOf(element)
|
||||
const originalDescriptor =
|
||||
Object.getOwnPropertyDescriptor(element, 'value') ??
|
||||
Object.getOwnPropertyDescriptor(proto, 'value')
|
||||
|
||||
// Intercept programmatic .value writes on the element
|
||||
// This catches cases where extensions or libraries set element.value directly
|
||||
try {
|
||||
Object.defineProperty(element, 'value', {
|
||||
get() {
|
||||
return originalDescriptor?.get?.call(this) ?? bridgedValue.value
|
||||
},
|
||||
set(newValue: string) {
|
||||
originalDescriptor?.set?.call(this, newValue)
|
||||
bridgedValue.value = newValue
|
||||
},
|
||||
configurable: true,
|
||||
enumerable: true
|
||||
})
|
||||
} catch {
|
||||
// If the descriptor is non-configurable, fall back to polling-free sync
|
||||
// via input events only
|
||||
}
|
||||
|
||||
// Listen for user-driven input events
|
||||
element.addEventListener('input', () => {
|
||||
// Read through the original descriptor to avoid infinite loops
|
||||
const currentValue = originalDescriptor?.get?.call(element) ?? element.value
|
||||
bridgedValue.value = currentValue
|
||||
})
|
||||
|
||||
// When the ref is written to externally, update the DOM element
|
||||
watch(bridgedValue, (newValue) => {
|
||||
const currentDomValue =
|
||||
originalDescriptor?.get?.call(element) ?? element.value
|
||||
if (currentDomValue !== newValue) {
|
||||
originalDescriptor?.set?.call(element, newValue)
|
||||
}
|
||||
})
|
||||
|
||||
return bridgedValue
|
||||
}
|
||||
@@ -178,7 +178,7 @@
|
||||
"uploadAlreadyInProgress": "Upload already in progress",
|
||||
"capture": "capture",
|
||||
"nodes": "Nodes",
|
||||
"nodesCount": "{count} nodes | {count} node | {count} nodes",
|
||||
"nodesCount": "{count} node | {count} nodes",
|
||||
"addNode": "Add a node...",
|
||||
"filterBy": "Filter by:",
|
||||
"filterByType": "Filter by {type}...",
|
||||
@@ -222,7 +222,7 @@
|
||||
"failed": "Failed",
|
||||
"cancelled": "Cancelled",
|
||||
"job": "Job",
|
||||
"asset": "{count} assets | {count} asset | {count} assets",
|
||||
"asset": "{count} asset | {count} assets",
|
||||
"untitled": "Untitled",
|
||||
"emDash": "—",
|
||||
"enabling": "Enabling {id}",
|
||||
@@ -3347,7 +3347,7 @@
|
||||
}
|
||||
},
|
||||
"errorOverlay": {
|
||||
"errorCount": "{count} ERRORS | {count} ERROR | {count} ERRORS",
|
||||
"errorCount": "{count} ERROR | {count} ERRORS",
|
||||
"seeErrors": "See Errors"
|
||||
},
|
||||
"help": {
|
||||
@@ -3357,7 +3357,7 @@
|
||||
"progressToast": {
|
||||
"importingModels": "Importing Models",
|
||||
"downloadingModel": "Downloading model...",
|
||||
"downloadsFailed": "{count} downloads failed | {count} download failed | {count} downloads failed",
|
||||
"downloadsFailed": "{count} download failed | {count} downloads failed",
|
||||
"allDownloadsCompleted": "All downloads completed",
|
||||
"noImportsInQueue": "No {filter} in queue",
|
||||
"failed": "Failed",
|
||||
@@ -3374,7 +3374,7 @@
|
||||
"exportingAssets": "Exporting Assets",
|
||||
"preparingExport": "Preparing export...",
|
||||
"exportError": "Export failed",
|
||||
"exportFailed": "{count} export failed | {count} export failed | {count} exports failed",
|
||||
"exportFailed": "{count} export failed | {count} exports failed",
|
||||
"allExportsCompleted": "All exports completed",
|
||||
"noExportsInQueue": "No {filter} exports in queue",
|
||||
"exportStarted": "Preparing ZIP download...",
|
||||
|
||||
@@ -1,79 +1,59 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ref } from 'vue'
|
||||
|
||||
import ComfyHubPublishDialog from '@/platform/workflow/sharing/components/publish/ComfyHubPublishDialog.vue'
|
||||
import type { ComfyHubProfile } from '@/schemas/apiSchema'
|
||||
|
||||
const mockFetchApi = vi.hoisted(() => vi.fn())
|
||||
const mockToastErrorHandler = vi.hoisted(() => vi.fn())
|
||||
const mockResolvedUserInfo = vi.hoisted(() => ({
|
||||
value: { id: 'user-a' }
|
||||
}))
|
||||
const mockFetchProfile = vi.hoisted(() => vi.fn())
|
||||
const mockGoToStep = vi.hoisted(() => vi.fn())
|
||||
const mockGoNext = vi.hoisted(() => vi.fn())
|
||||
const mockGoBack = vi.hoisted(() => vi.fn())
|
||||
const mockOpenProfileCreationStep = vi.hoisted(() => vi.fn())
|
||||
const mockCloseProfileCreationStep = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/scripts/api', () => ({
|
||||
api: {
|
||||
fetchApi: mockFetchApi
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/auth/useCurrentUser', () => ({
|
||||
useCurrentUser: () => ({
|
||||
resolvedUserInfo: mockResolvedUserInfo
|
||||
vi.mock(
|
||||
'@/platform/workflow/sharing/composables/useComfyHubProfileGate',
|
||||
() => ({
|
||||
useComfyHubProfileGate: () => ({
|
||||
fetchProfile: mockFetchProfile
|
||||
})
|
||||
})
|
||||
}))
|
||||
)
|
||||
|
||||
vi.mock('@/composables/useErrorHandling', () => ({
|
||||
useErrorHandling: () => ({
|
||||
toastErrorHandler: mockToastErrorHandler
|
||||
vi.mock(
|
||||
'@/platform/workflow/sharing/composables/useComfyHubPublishWizard',
|
||||
() => ({
|
||||
useComfyHubPublishWizard: () => ({
|
||||
currentStep: ref('finish'),
|
||||
formData: ref({
|
||||
name: '',
|
||||
description: '',
|
||||
workflowType: '',
|
||||
tags: [],
|
||||
thumbnailType: 'image',
|
||||
thumbnailFile: null,
|
||||
comparisonBeforeFile: null,
|
||||
comparisonAfterFile: null,
|
||||
exampleImages: [],
|
||||
selectedExampleIds: []
|
||||
}),
|
||||
isFirstStep: ref(false),
|
||||
isLastStep: ref(true),
|
||||
goToStep: mockGoToStep,
|
||||
goNext: mockGoNext,
|
||||
goBack: mockGoBack,
|
||||
openProfileCreationStep: mockOpenProfileCreationStep,
|
||||
closeProfileCreationStep: mockCloseProfileCreationStep
|
||||
})
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/platform/workflow/management/stores/workflowStore', () => ({
|
||||
useWorkflowStore: () => ({
|
||||
activeWorkflow: { filename: 'test-workflow' }
|
||||
})
|
||||
}))
|
||||
|
||||
const mockProfile: ComfyHubProfile = {
|
||||
username: 'testuser',
|
||||
name: 'Test User',
|
||||
description: 'A test profile'
|
||||
}
|
||||
|
||||
function mockSuccessResponse(data?: unknown) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => data ?? mockProfile
|
||||
} as Response
|
||||
}
|
||||
|
||||
function mockErrorResponse(status = 404) {
|
||||
return {
|
||||
ok: false,
|
||||
status,
|
||||
json: async () => ({ message: 'Not found' })
|
||||
} as Response
|
||||
}
|
||||
|
||||
// Reset module-level singleton state in useComfyHubProfileGate between tests
|
||||
async function resetProfileGateSingleton() {
|
||||
const { useComfyHubProfileGate } =
|
||||
await import('@/platform/workflow/sharing/composables/useComfyHubProfileGate')
|
||||
const gate = useComfyHubProfileGate()
|
||||
gate.hasProfile.value = null
|
||||
gate.profile.value = null
|
||||
gate.isCheckingProfile.value = false
|
||||
gate.isFetchingProfile.value = false
|
||||
}
|
||||
)
|
||||
|
||||
describe('ComfyHubPublishDialog', () => {
|
||||
const onClose = vi.fn()
|
||||
|
||||
beforeEach(async () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockResolvedUserInfo.value = { id: 'user-a' }
|
||||
mockFetchApi.mockResolvedValue(mockErrorResponse())
|
||||
await resetProfileGateSingleton()
|
||||
mockFetchProfile.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
function createWrapper() {
|
||||
@@ -98,7 +78,7 @@ describe('ComfyHubPublishDialog', () => {
|
||||
},
|
||||
ComfyHubPublishWizardContent: {
|
||||
template:
|
||||
'<div><button data-testid="require-profile" @click="$props.onRequireProfile()" /><button data-testid="gate-complete" @click="$props.onGateComplete()" /><button data-testid="gate-close" @click="$props.onGateClose()" /><span data-testid="current-step">{{ $props.currentStep }}</span></div>',
|
||||
'<div><button data-testid="require-profile" @click="$props.onRequireProfile()" /><button data-testid="gate-complete" @click="$props.onGateComplete()" /><button data-testid="gate-close" @click="$props.onGateClose()" /></div>',
|
||||
props: [
|
||||
'currentStep',
|
||||
'formData',
|
||||
@@ -108,9 +88,7 @@ describe('ComfyHubPublishDialog', () => {
|
||||
'onGoBack',
|
||||
'onRequireProfile',
|
||||
'onGateComplete',
|
||||
'onGateClose',
|
||||
'onUpdateFormData',
|
||||
'onPublish'
|
||||
'onGateClose'
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -118,62 +96,44 @@ describe('ComfyHubPublishDialog', () => {
|
||||
})
|
||||
}
|
||||
|
||||
it('prefetches profile on mount via real composable', async () => {
|
||||
it('starts in publish wizard mode and prefetches profile asynchronously', async () => {
|
||||
createWrapper()
|
||||
await flushPromises()
|
||||
|
||||
expect(mockFetchApi).toHaveBeenCalledWith('/hub/profile')
|
||||
expect(mockFetchProfile).toHaveBeenCalledWith()
|
||||
})
|
||||
|
||||
it('starts on the describe step with real wizard composable', async () => {
|
||||
const wrapper = createWrapper()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('[data-testid="current-step"]').text()).toBe('describe')
|
||||
})
|
||||
|
||||
it('switches to profileCreation step when require-profile is triggered', async () => {
|
||||
it('switches to profile creation step when final-step publish requires profile', async () => {
|
||||
const wrapper = createWrapper()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('[data-testid="require-profile"]').trigger('click')
|
||||
|
||||
expect(wrapper.find('[data-testid="current-step"]').text()).toBe(
|
||||
'profileCreation'
|
||||
)
|
||||
expect(mockOpenProfileCreationStep).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('returns to finish step and re-fetches profile after gate complete', async () => {
|
||||
mockFetchApi.mockResolvedValue(mockSuccessResponse())
|
||||
it('returns to finish state after gate complete and does not auto-close', async () => {
|
||||
const wrapper = createWrapper()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('[data-testid="require-profile"]').trigger('click')
|
||||
expect(wrapper.find('[data-testid="current-step"]').text()).toBe(
|
||||
'profileCreation'
|
||||
)
|
||||
|
||||
await wrapper.find('[data-testid="gate-complete"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('[data-testid="current-step"]').text()).toBe('finish')
|
||||
// Initial prefetch + force re-fetch after gate complete
|
||||
expect(mockFetchApi).toHaveBeenCalledTimes(2)
|
||||
expect(mockOpenProfileCreationStep).toHaveBeenCalledOnce()
|
||||
expect(mockCloseProfileCreationStep).toHaveBeenCalledOnce()
|
||||
expect(mockFetchProfile).toHaveBeenCalledWith({ force: true })
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns to finish step when profile gate is closed', async () => {
|
||||
it('returns to finish state when profile gate is closed', async () => {
|
||||
const wrapper = createWrapper()
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.find('[data-testid="require-profile"]').trigger('click')
|
||||
expect(wrapper.find('[data-testid="current-step"]').text()).toBe(
|
||||
'profileCreation'
|
||||
)
|
||||
|
||||
await wrapper.find('[data-testid="gate-close"]').trigger('click')
|
||||
|
||||
expect(wrapper.find('[data-testid="current-step"]').text()).toBe('finish')
|
||||
expect(mockOpenProfileCreationStep).toHaveBeenCalledOnce()
|
||||
expect(mockCloseProfileCreationStep).toHaveBeenCalledOnce()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import _ from 'es-toolkit/compat'
|
||||
import { type Component, toRaw } from 'vue'
|
||||
|
||||
import { useDomValueBridge } from '@/composables/element/useDomValueBridge'
|
||||
import { useChainCallback } from '@/composables/functional/useChainCallback'
|
||||
import {
|
||||
LGraphNode,
|
||||
@@ -379,6 +380,16 @@ export const addWidget = <W extends BaseDOMWidget<object | string>>(
|
||||
})
|
||||
}
|
||||
|
||||
function isValueElement(
|
||||
el: HTMLElement
|
||||
): el is HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement {
|
||||
return (
|
||||
el instanceof HTMLInputElement ||
|
||||
el instanceof HTMLTextAreaElement ||
|
||||
el instanceof HTMLSelectElement
|
||||
)
|
||||
}
|
||||
|
||||
LGraphNode.prototype.addDOMWidget = function <
|
||||
T extends HTMLElement,
|
||||
V extends object | string
|
||||
@@ -389,6 +400,19 @@ LGraphNode.prototype.addDOMWidget = function <
|
||||
element: T,
|
||||
options: DOMWidgetOptions<V> = {}
|
||||
): DOMWidget<T, V> {
|
||||
// Auto-bridge value-bearing elements when no getValue/setValue provided.
|
||||
// This gives extension authors automatic widgetValueStore integration.
|
||||
if (!options.getValue && !options.setValue && isValueElement(element)) {
|
||||
const bridgedValue = useDomValueBridge(element)
|
||||
options = {
|
||||
...options,
|
||||
getValue: (() => bridgedValue.value) as () => V,
|
||||
setValue: ((v: V) => {
|
||||
bridgedValue.value = String(v)
|
||||
}) as (v: V) => void
|
||||
}
|
||||
}
|
||||
|
||||
const widget = new DOMWidgetImpl({
|
||||
node: this,
|
||||
name,
|
||||
|
||||
Reference in New Issue
Block a user