diff --git a/.oxlintrc.json b/.oxlintrc.json index 459c0c8017d..df030c1464f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -143,6 +143,7 @@ "**/{__test__,__tests__,__fixtures__}/**/*.{ts,tsx}" ], "rules": { + "comfy/no-import-actual": "error", "comfy/use-global-pinia": "error" } }, diff --git a/apps/website/package.json b/apps/website/package.json index 613cb7caba7..7cf0d28ff41 100644 --- a/apps/website/package.json +++ b/apps/website/package.json @@ -74,6 +74,7 @@ "@testing-library/jest-dom": "catalog:", "@testing-library/user-event": "catalog:", "@testing-library/vue": "catalog:", + "@total-typescript/shoehorn": "catalog:", "@types/leaflet": "catalog:", "@vitejs/plugin-vue": "catalog:", "astro": "catalog:", diff --git a/apps/website/scripts/router-gemini-video.test.ts b/apps/website/scripts/router-gemini-video.test.ts index f1ed66632b5..68fe3f26eaf 100644 --- a/apps/website/scripts/router-gemini-video.test.ts +++ b/apps/website/scripts/router-gemini-video.test.ts @@ -1,17 +1,13 @@ import { expect, it, vi } from 'vitest' import { prepareModelRouterRender } from '../src/config/router-render' -import { loadWorkshopExampleFile } from '../src/config/workshop-example-file' +import { loadWorkshopExampleFile } from '../src/config/workshop-example-file-loader' import { getRouterWorkshopModelDetail } from '../src/config/workshop-router-content' import { prepareWorkshopRequestCallback } from '../src/config/workshop-request-callbacks' -vi.mock( - import('../src/config/workshop-example-file'), - async (importOriginal) => ({ - ...(await importOriginal()), - loadWorkshopExampleFile: vi.fn() - }) -) +vi.mock(import('../src/config/workshop-example-file-loader'), () => ({ + loadWorkshopExampleFile: vi.fn() +})) it.for([{}, { image_url: 'https://example.com/still.png' }])( 'rejects an edit without source video even when an image is present', diff --git a/apps/website/scripts/router-render.test.ts b/apps/website/scripts/router-render.test.ts index 121ee632368..315dd412c07 100644 --- a/apps/website/scripts/router-render.test.ts +++ b/apps/website/scripts/router-render.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { loadWorkshopExampleFile } from '../src/config/workshop-example-file' +import { loadWorkshopExampleFile } from '../src/config/workshop-example-file-loader' import { runWorkshopRouter } from '../src/config/workshop-router' import { WorkshopRouterError } from '../src/config/workshop-router-errors' import { @@ -9,18 +9,13 @@ import { router_render } from './router-render' -vi.mock(import('../src/config/workshop-router'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock(import('../src/config/workshop-router'), () => ({ runWorkshopRouter: vi.fn() })) -vi.mock( - import('../src/config/workshop-example-file'), - async (importOriginal) => ({ - ...(await importOriginal()), - loadWorkshopExampleFile: vi.fn() - }) -) +vi.mock(import('../src/config/workshop-example-file-loader'), () => ({ + loadWorkshopExampleFile: vi.fn() +})) describe('router_render', () => { it.for([ diff --git a/apps/website/src/components/auth/AuthEmailForm.test.ts b/apps/website/src/components/auth/AuthEmailForm.test.ts index e3121f07703..55a7b81cef6 100644 --- a/apps/website/src/components/auth/AuthEmailForm.test.ts +++ b/apps/website/src/components/auth/AuthEmailForm.test.ts @@ -2,7 +2,11 @@ import userEvent from '@testing-library/user-event' import { render, screen, waitFor } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { defineComponent } from 'vue' + +import type { + TurnstileApi, + TurnstileRenderOptions +} from '@comfyorg/account/turnstileScript' import AuthEmailForm from './AuthEmailForm.vue' @@ -10,28 +14,18 @@ const widgetBehavior = vi.hoisted(() => ({ mode: 'silent' as 'silent' | 'unavailable' | 'token', reset: vi.fn() })) -vi.mock(import('@comfyorg/account/vue'), async (importOriginal) => { - const { h, onMounted } = await import('vue') - return { - ...(await (importOriginal as () => Promise)()), - TurnstileWidget: defineComponent({ - name: 'TurnstileWidgetStub', - emits: ['update:token', 'update:unavailable'], - setup(_, { emit, expose }) { - expose({ reset: widgetBehavior.reset }) - onMounted(() => { - if (widgetBehavior.mode === 'unavailable') { - emit('update:unavailable', true) - } - if (widgetBehavior.mode === 'token') { - emit('update:token', 'cf-token') - } - }) - return () => h('div', { 'data-testid': 'turnstile-stub' }) - } - }) - } -}) +const turnstileApi = vi.hoisted( + () => + ({ + render: vi.fn(), + reset: widgetBehavior.reset, + remove: vi.fn() + }) satisfies TurnstileApi +) + +vi.mock(import('@comfyorg/account/turnstileScript'), () => ({ + loadTurnstile: () => Promise.resolve(turnstileApi) +})) vi.mock(import('../../scripts/posthog'), async () => { const { ref } = await import('vue') @@ -44,6 +38,17 @@ const submitButton = (name: RegExp) => beforeEach(() => { widgetBehavior.mode = 'silent' widgetBehavior.reset.mockReset() + turnstileApi.render.mockImplementation( + (_container: string | HTMLElement, options: TurnstileRenderOptions) => { + if (widgetBehavior.mode === 'unavailable') { + options['error-callback']?.() + } + if (widgetBehavior.mode === 'token') { + options.callback?.('cf-token') + } + return 'widget-id' + } + ) }) describe('AuthEmailForm sign-in', () => { diff --git a/apps/website/src/components/auth/AuthSignIn.test.ts b/apps/website/src/components/auth/AuthSignIn.test.ts index 27da4aabb10..f603d02082b 100644 --- a/apps/website/src/components/auth/AuthSignIn.test.ts +++ b/apps/website/src/components/auth/AuthSignIn.test.ts @@ -4,6 +4,10 @@ import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' import { AUTH_ERROR_MESSAGES } from '@comfyorg/account/firebaseAuthError' +import type { + TurnstileApi, + TurnstileRenderOptions +} from '@comfyorg/account/turnstileScript' import { removeAllToasts, useAuthToasts } from '../../config/auth-toast-state' import AuthSignIn from './AuthSignIn.vue' @@ -47,20 +51,18 @@ vi.mock(import('../../scripts/posthog'), async () => { } }) -vi.mock(import('@comfyorg/account/vue'), async (importOriginal) => { - const { defineComponent, h, onMounted } = await import('vue') - return { - ...(await (importOriginal as () => Promise)()), - TurnstileWidget: defineComponent({ - emits: ['update:token', 'update:unavailable'], - setup(_, { emit, expose }) { - expose({ reset: handles.turnstileReset }) - onMounted(() => emit('update:token', 'cf-token')) - return () => h('div', { 'data-testid': 'turnstile' }) - } - }) - } -}) +const turnstileApi = vi.hoisted( + () => + ({ + render: vi.fn(), + reset: handles.turnstileReset, + remove: vi.fn() + }) satisfies TurnstileApi +) + +vi.mock(import('@comfyorg/account/turnstileScript'), () => ({ + loadTurnstile: () => Promise.resolve(turnstileApi) +})) vi.mock(import('@comfyorg/account/webviewDetection'), () => ({ isEmbeddedWebView: () => handles.embedded @@ -142,6 +144,12 @@ beforeEach(() => { handles.emailSignUp.mockReset() handles.provision.mockReset().mockResolvedValue(undefined) handles.turnstileReset.mockReset() + turnstileApi.render.mockImplementation( + (_container: string | HTMLElement, options: TurnstileRenderOptions) => { + options.callback?.('cf-token') + return 'widget-id' + } + ) handles.isProvisioningError.mockReset().mockReturnValue(false) handles.isNewUser.mockReset().mockReturnValue(false) handles.captureAuthCompleted.mockClear() diff --git a/apps/website/src/components/hero/camera/CameraWidget.test.ts b/apps/website/src/components/hero/camera/CameraWidget.test.ts index 12a7973fa76..460a92e6f11 100644 --- a/apps/website/src/components/hero/camera/CameraWidget.test.ts +++ b/apps/website/src/components/hero/camera/CameraWidget.test.ts @@ -1,39 +1,29 @@ // @vitest-environment happy-dom +import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' import { PerspectiveCamera, Vector3 } from 'three' -import type * as ThreeModule from 'three' -import type { Camera, Scene } from 'three' +import type { Camera, Scene, WebGLRenderer as WebGLRendererType } from 'three' +import { WebGLRenderer } from 'three/src/renderers/WebGLRenderer.js' import { CameraWidget } from './CameraWidget' import type { CameraState } from './types' -// Everything except the GPU-bound renderer runs for real: scene graph, -// raycasting and drag math are the code under test. The fake renderer updates -// world matrices the way WebGLRenderer.render does, so raycasts see current -// object positions. -vi.mock(import('three'), async (importOriginal) => { - const three = await importOriginal() - type WebGLRendererContract = Pick< - ThreeModule.WebGLRenderer, - 'domElement' | 'outputColorSpace' | 'setSize' | 'setPixelRatio' | 'dispose' - > - class FakeWebGLRenderer implements WebGLRendererContract { - domElement = document.createElement('canvas') - outputColorSpace: ThreeModule.ColorSpace = '' - setSize() {} - setPixelRatio() {} - dispose() {} +vi.mock(import('three/src/renderers/WebGLRenderer.js'), () => ({ + WebGLRenderer: vi.fn() +})) + +function fakeRenderer() { + return fromPartial({ + domElement: document.createElement('canvas'), + setSize: vi.fn(), + setPixelRatio: vi.fn(), + dispose: vi.fn(), render(scene: Scene, camera: Camera) { scene.updateMatrixWorld(true) camera.updateMatrixWorld(true) } - } - return { - ...three, - WebGLRenderer: - FakeWebGLRenderer as unknown as typeof ThreeModule.WebGLRenderer - } -}) + }) +} const SIZE = 300 @@ -131,10 +121,11 @@ describe('CameraWidget', () => { beforeEach(() => { FakeImage.instances = [] FakeResizeObserver.instances = [] + vi.mocked(WebGLRenderer).mockImplementation(fakeRenderer) vi.stubGlobal('Image', FakeImage) vi.stubGlobal('ResizeObserver', FakeResizeObserver) vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue( - fake2dContext as unknown as CanvasRenderingContext2D + fromPartial(fake2dContext) ) }) diff --git a/apps/website/src/components/hero/camera/CameraWidget.ts b/apps/website/src/components/hero/camera/CameraWidget.ts index 1a1b099b26a..1377eddd8cd 100644 --- a/apps/website/src/components/hero/camera/CameraWidget.ts +++ b/apps/website/src/components/hero/camera/CameraWidget.ts @@ -31,10 +31,10 @@ import { TorusGeometry, TubeGeometry, Vector2, - Vector3, - WebGLRenderer + Vector3 } from 'three' import type { Camera, Material } from 'three' +import { WebGLRenderer } from 'three/src/renderers/WebGLRenderer.js' import type { CameraPalette, CameraState, CameraWidgetOptions } from './types' diff --git a/apps/website/src/components/workshop/ModelDetail.test.ts b/apps/website/src/components/workshop/ModelDetail.test.ts index e95c04ef714..4760e851f44 100644 --- a/apps/website/src/components/workshop/ModelDetail.test.ts +++ b/apps/website/src/components/workshop/ModelDetail.test.ts @@ -49,19 +49,16 @@ vi.mock(import('../../config/workshop-session-state'), () => ({ }) })) -vi.mock(import('../../scripts/posthog'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock(import('../../scripts/posthog'), () => ({ useWorkshopAuthFlag: () => computed(() => auth.enabled.value), useWorkshopAuthFlagSettled: () => computed(() => auth.flagSettled.value) })) -vi.mock(import('../../config/workshop-router'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock(import('../../config/workshop-router'), () => ({ runWorkshopRouter: vi.fn() })) -vi.mock(import('../../config/workshop-credits'), async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock(import('../../config/workshop-credits'), () => ({ refreshWorkshopCredits: vi.fn().mockResolvedValue(undefined), useWorkshopCredits: () => ({ balance: computed(() => credits.balance.value), diff --git a/apps/website/src/components/workshop/PlaygroundOutput.test.ts b/apps/website/src/components/workshop/PlaygroundOutput.test.ts index dd87fd3d3d6..30b158dde31 100644 --- a/apps/website/src/components/workshop/PlaygroundOutput.test.ts +++ b/apps/website/src/components/workshop/PlaygroundOutput.test.ts @@ -10,8 +10,7 @@ import { WORKSHOP_CLOUD_BASE_URL } from '../../config/workshop-env' import PlaygroundOutput from './PlaygroundOutput.vue' import { downloadOutput } from '../../config/workshop-output-download' -vi.mock(import('../../config/workshop-output-download'), async (original) => ({ - ...(await original()), +vi.mock(import('../../config/workshop-output-download'), () => ({ downloadOutput: vi.fn(async () => true) })) diff --git a/apps/website/src/config/workshop-creator-request.ts b/apps/website/src/config/workshop-creator-request.ts index 928ef1153f1..01ef7b9baf1 100644 --- a/apps/website/src/config/workshop-creator-request.ts +++ b/apps/website/src/config/workshop-creator-request.ts @@ -7,7 +7,7 @@ import { workshopFileBase64 } from './workshop-file-encoding' import { WorkshopRouterError } from './workshop-router-errors' import { renderWorkshopRequestTemplate } from './workshop-request-template' import { prepareWorkshopRequestCallback } from './workshop-request-callbacks' -import { loadWorkshopExampleFile } from './workshop-example-file' +import { loadWorkshopExampleFile } from './workshop-example-file-loader' import { MAX_REQUEST_BYTES } from './workshop-limits' export interface EncodedWorkshopFile { diff --git a/apps/website/src/config/workshop-example-file-loader.ts b/apps/website/src/config/workshop-example-file-loader.ts new file mode 100644 index 00000000000..0fb21f6ab6e --- /dev/null +++ b/apps/website/src/config/workshop-example-file-loader.ts @@ -0,0 +1,64 @@ +import type { FileValue } from './workshop-playground' + +import { + WORKSHOP_EXAMPLE_MIME_TYPES, + workshopExampleFile +} from './workshop-example-file' + +const files = new WeakMap() +const MAX_BYTES = 7 * 1024 * 1024 + +export async function loadWorkshopExampleFile( + value: FileValue, + signal: AbortSignal +): Promise { + signal.throwIfAborted() + const cached = files.get(value) + if (cached) return cached + if (!value.sourceUrl || !workshopExampleFile(value.sourceUrl)) + throw new Error('Invalid example media URL') + const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30_000)]) + const response = await fetch(value.sourceUrl, { + signal: requestSignal, + credentials: 'omit', + redirect: 'error' + }) + if ( + !response.ok || + Number(response.headers.get('Content-Length')) > MAX_BYTES + ) { + await response.body?.cancel() + throw new Error('Example media unavailable or too large') + } + const type = + response.headers.get('Content-Type')?.split(';')[0].trim().toLowerCase() ?? + '' + if (![...WORKSHOP_EXAMPLE_MIME_TYPES.values()].includes(type)) { + await response.body?.cancel() + throw new Error('Invalid example media type') + } + const reader = response.body?.getReader() + if (!reader) throw new Error('Empty example media') + const chunks: Uint8Array[] = [] + let bytes = 0 + try { + for (;;) { + requestSignal.throwIfAborted() + const { done, value: chunk } = await reader.read() + if (done) break + bytes += chunk.byteLength + if (bytes > MAX_BYTES) throw new Error('Example media too large') + chunks.push(new Uint8Array(chunk)) + } + } catch (error) { + await reader.cancel().catch(() => {}) + throw error + } finally { + reader.releaseLock() + } + signal.throwIfAborted() + if (!bytes) throw new Error('Empty example media') + const file = new File(chunks, value.name, { type }) + files.set(value, file) + return file +} diff --git a/apps/website/src/config/workshop-example-file.test.ts b/apps/website/src/config/workshop-example-file.test.ts index 5d61eb5cd14..1e0297adc32 100644 --- a/apps/website/src/config/workshop-example-file.test.ts +++ b/apps/website/src/config/workshop-example-file.test.ts @@ -1,9 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { - loadWorkshopExampleFile, - workshopExampleFile -} from './workshop-example-file' +import { workshopExampleFile } from './workshop-example-file' +import { loadWorkshopExampleFile } from './workshop-example-file-loader' import { getRouterWorkshopModelDetail } from './workshop-router-content' import { defaultValues, schemaForModel } from './workshop-playground' import { prepareWorkshopRouterInput } from './workshop-request' diff --git a/apps/website/src/config/workshop-example-file.ts b/apps/website/src/config/workshop-example-file.ts index af23ad1ec91..f36a90782db 100644 --- a/apps/website/src/config/workshop-example-file.ts +++ b/apps/website/src/config/workshop-example-file.ts @@ -1,7 +1,7 @@ import type { FileValue } from './workshop-playground' import { isHttpImageSource } from './workshop-image-source' -const MIME_TYPES = new Map([ +export const WORKSHOP_EXAMPLE_MIME_TYPES = new Map([ ['png', 'image/png'], ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'], @@ -13,8 +13,6 @@ const MIME_TYPES = new Map([ ['wav', 'audio/wav'], ['m4a', 'audio/mp4'] ]) -const files = new WeakMap() -const MAX_BYTES = 7 * 1024 * 1024 export function workshopExampleFile( source: string, @@ -23,7 +21,9 @@ export function workshopExampleFile( if (!isHttpImageSource(source)) return const name = new URL(source).pathname.split('/').at(-1) || 'example' const type = - MIME_TYPES.get(name.split('.').at(-1)?.toLowerCase() ?? '') ?? fallbackType + WORKSHOP_EXAMPLE_MIME_TYPES.get( + name.split('.').at(-1)?.toLowerCase() ?? '' + ) ?? fallbackType return { name, type, size: 0, previewUrl: source, sourceUrl: source } } @@ -42,58 +42,3 @@ export function workshopExampleFiles( if (!result.length || (!multiple && result.length > 1)) return return multiple ? result : result[0] } - -export async function loadWorkshopExampleFile( - value: FileValue, - signal: AbortSignal -): Promise { - signal.throwIfAborted() - const cached = files.get(value) - if (cached) return cached - if (!value.sourceUrl || !workshopExampleFile(value.sourceUrl)) - throw new Error('Invalid example media URL') - const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30_000)]) - const response = await fetch(value.sourceUrl, { - signal: requestSignal, - credentials: 'omit', - redirect: 'error' - }) - if ( - !response.ok || - Number(response.headers.get('Content-Length')) > MAX_BYTES - ) { - await response.body?.cancel() - throw new Error('Example media unavailable or too large') - } - const type = - response.headers.get('Content-Type')?.split(';')[0].trim().toLowerCase() ?? - '' - if (![...MIME_TYPES.values()].includes(type)) { - await response.body?.cancel() - throw new Error('Invalid example media type') - } - const reader = response.body?.getReader() - if (!reader) throw new Error('Empty example media') - const chunks: Uint8Array[] = [] - let bytes = 0 - try { - for (;;) { - requestSignal.throwIfAborted() - const { done, value: chunk } = await reader.read() - if (done) break - bytes += chunk.byteLength - if (bytes > MAX_BYTES) throw new Error('Example media too large') - chunks.push(new Uint8Array(chunk)) - } - } catch (error) { - await reader.cancel().catch(() => {}) - throw error - } finally { - reader.releaseLock() - } - signal.throwIfAborted() - if (!bytes) throw new Error('Empty example media') - const file = new File(chunks, value.name, { type }) - files.set(value, file) - return file -} diff --git a/apps/website/src/config/workshop-request.ts b/apps/website/src/config/workshop-request.ts index 53912810d47..2df4792e4ea 100644 --- a/apps/website/src/config/workshop-request.ts +++ b/apps/website/src/config/workshop-request.ts @@ -20,7 +20,7 @@ import { workshopFileBase64 } from './workshop-file-encoding' import { prepareWorkshopCreatorRequest } from './workshop-creator-request' import type { WorkshopUrlEncoder } from './workshop-url-input' import { resolveWorkshopUrlInputs } from './workshop-url-input' -import { loadWorkshopExampleFile } from './workshop-example-file' +import { loadWorkshopExampleFile } from './workshop-example-file-loader' import { MAX_REQUEST_BYTES } from './workshop-limits' const ACCEPT: Record = { diff --git a/apps/website/src/config/workshop-url-input.ts b/apps/website/src/config/workshop-url-input.ts index 94eef750647..bf56050e2db 100644 --- a/apps/website/src/config/workshop-url-input.ts +++ b/apps/website/src/config/workshop-url-input.ts @@ -2,10 +2,8 @@ import type { FieldSchema, FileValue, FormValues } from './workshop-playground' import { urlUploadField, validateForm } from './workshop-playground' import { WorkshopRouterError } from './workshop-router-errors' import { isHttpImageSource } from './workshop-image-source' -import { - loadWorkshopExampleFile, - workshopExampleFile -} from './workshop-example-file' +import { workshopExampleFile } from './workshop-example-file' +import { loadWorkshopExampleFile } from './workshop-example-file-loader' const downloadedSources = new Map() const formSources = new WeakMap>() diff --git a/apps/website/src/routes/models/model-page.test.ts b/apps/website/src/routes/models/model-page.test.ts index f8122d04ef7..3137c488171 100644 --- a/apps/website/src/routes/models/model-page.test.ts +++ b/apps/website/src/routes/models/model-page.test.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { WorkshopModelDetail } from '../../config/models-catalogue' +import type { + WorkshopFilter, + WorkshopModelDetail +} from '../../config/models-catalogue' import { prepareModelPage } from './model-page' const mocks = vi.hoisted(() => ({ @@ -18,9 +21,13 @@ vi.mock(import('../../config/workshop-related'), () => ({ vi.mock(import('../../config/workshop-node-pricing'), () => ({ estimateWorkshopNodePrice: mocks.price })) -vi.mock(import('../../config/models-catalogue'), async (importOriginal) => ({ - ...(await importOriginal()), - getWorkshopModel: mocks.successor +vi.mock(import('../../config/models-catalogue'), () => ({ + catalogSearch: ({ capabilities = [] }: Partial) => + new URLSearchParams( + capabilities.map((capability) => ['capability', capability]) + ).toString(), + getWorkshopModel: mocks.successor, + workshopModels: [] })) const model: WorkshopModelDetail = { diff --git a/apps/website/src/templates/events/EventsDirectoryRow.test.ts b/apps/website/src/templates/events/EventsDirectoryRow.test.ts index b0d2de5dae8..086cdbe72aa 100644 --- a/apps/website/src/templates/events/EventsDirectoryRow.test.ts +++ b/apps/website/src/templates/events/EventsDirectoryRow.test.ts @@ -1,11 +1,9 @@ // @vitest-environment happy-dom import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' -import type * as vueuseModule from '@vueuse/core' - import type { ComfyEvent } from '../../data/events' import { directoryRows } from '../../utils/eventsDirectory' @@ -16,18 +14,17 @@ const localized = (en: string) => ({ en, 'zh-CN': en }) // Captures the resize callback so a test can feed it a fake overflow entry; // happy-dom performs no layout, so the clamp can never trip on its own. const { resizeCallbacks } = vi.hoisted(() => ({ - resizeCallbacks: [] as Array<(entries: Array<{ target: Element }>) => void> + resizeCallbacks: [] as ResizeObserverCallback[] })) -vi.mock(import('@vueuse/core'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - useResizeObserver: vi.fn((_el: unknown, cb: unknown) => { - resizeCallbacks.push(cb as (typeof resizeCallbacks)[number]) - return { stop: () => {} } - }) as unknown as typeof actual.useResizeObserver +class MockResizeObserver implements ResizeObserver { + constructor(callback: ResizeObserverCallback, record = true) { + if (record) resizeCallbacks.push(callback) } -}) + + observe() {} + unobserve() {} + disconnect() {} +} const makeEvent = (overrides: Partial = {}): ComfyEvent => ({ id: 'meetup-1', @@ -46,6 +43,11 @@ const AFTER = new Date('2027-01-01T00:00:00Z') const BEFORE = new Date('2026-01-01T00:00:00Z') describe('EventsDirectoryRow', () => { + beforeEach(() => { + resizeCallbacks.length = 0 + vi.stubGlobal('ResizeObserver', MockResizeObserver) + }) + it('marks past rows with a Past pill and leaves upcoming rows without one', () => { const { unmount } = render(EventsDirectoryRow, { props: { row: rowOf(makeEvent(), AFTER) } @@ -97,7 +99,16 @@ describe('EventsDirectoryRow', () => { const desc = screen.getByText('A description that could run long.') Object.defineProperty(desc, 'scrollHeight', { value: 64 }) Object.defineProperty(desc, 'clientHeight', { value: 32 }) - for (const cb of resizeCallbacks) cb([{ target: desc }]) + const entry: ResizeObserverEntry = { + target: desc, + borderBoxSize: [], + contentBoxSize: [], + contentRect: desc.getBoundingClientRect(), + devicePixelContentBoxSize: [] + } + for (const cb of resizeCallbacks) { + cb([entry], new MockResizeObserver(cb, false)) + } await nextTick() await userEvent.click(screen.getByRole('button', { name: 'Read more' })) diff --git a/apps/website/src/templates/events/EventsDirectorySection.test.ts b/apps/website/src/templates/events/EventsDirectorySection.test.ts index b8b1e7c0e3d..52f8036ced8 100644 --- a/apps/website/src/templates/events/EventsDirectorySection.test.ts +++ b/apps/website/src/templates/events/EventsDirectorySection.test.ts @@ -1,17 +1,16 @@ // @vitest-environment happy-dom import userEvent from '@testing-library/user-event' import { render, screen, within } from '@testing-library/vue' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { nextTick } from 'vue' import type { ComfyEvent } from '../../data/events' -import type * as eventsModule from '../../data/events' import EventsDirectorySection from './EventsDirectorySection.vue' // Three fixtures against a fixed clock: an upcoming hackathon and a past // meetup with coordinates, plus a virtual workshop without any. -const { NOW, fixtureEvents } = vi.hoisted(() => { +const { NOW, fixtureEvents } = (() => { const localized = (en: string) => ({ en, 'zh-CN': en }) const paris: ComfyEvent = { id: 'paris', @@ -46,12 +45,7 @@ const { NOW, fixtureEvents } = vi.hoisted(() => { NOW: new Date('2026-06-01T00:00:00Z'), fixtureEvents: [paris, online, tokyo] } -}) - -vi.mock(import('../../data/events'), async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, directoryEvents: fixtureEvents, eventsDerivedAt: NOW } -}) +})() // The real map pulls in Leaflet at mount, so it is replaced with one button // per marker that replays the block's `select` event. @@ -75,7 +69,7 @@ const stubs = { function renderSection() { return render(EventsDirectorySection, { - props: { locale: 'en' }, + props: { locale: 'en', events: fixtureEvents, derivedAt: NOW }, global: { stubs } }) } diff --git a/apps/website/src/templates/events/EventsDirectorySection.vue b/apps/website/src/templates/events/EventsDirectorySection.vue index f3b6ec79aca..c290882c1b7 100644 --- a/apps/website/src/templates/events/EventsDirectorySection.vue +++ b/apps/website/src/templates/events/EventsDirectorySection.vue @@ -5,6 +5,7 @@ import { computed, reactive, ref, watch } from 'vue' import { cn } from '@comfyorg/tailwind-utils' import type { MapPinMarker } from '../../components/blocks/MapPins01.vue' +import type { ComfyEvent } from '../../data/events' import type { Locale } from '../../i18n/translations' import type { EventsDirectoryView } from '../../utils/eventsDirectory' @@ -23,7 +24,15 @@ import { } from '../../utils/eventsDirectory' import EventsDirectoryList from './EventsDirectoryList.vue' -const { locale = 'en' } = defineProps<{ locale?: Locale }>() +const { + locale = 'en', + events = directoryEvents, + derivedAt = eventsDerivedAt +} = defineProps<{ + locale?: Locale + events?: readonly ComfyEvent[] + derivedAt?: Date +}>() // Search, type and organizer feed whichever view is active, so the whole // section is one reactive model: three filter fields plus the view. Everything @@ -33,7 +42,7 @@ const view = ref('map') const sort = ref<'latest' | 'oldest'>('latest') const visibleEvents = computed(() => - filterDirectoryEvents(directoryEvents, filters, locale) + filterDirectoryEvents(events, filters, locale) ) // `directoryEvents` is latest-first, so Oldest is a plain reversal of the @@ -50,7 +59,7 @@ const sortedEvents = computed(() => // clock that ordered `directoryEvents`, so a row's position and its CTA can // never straddle the upcoming/past boundary. const rows = computed(() => - directoryRows(sortedEvents.value, locale, eventsDerivedAt) + directoryRows(sortedEvents.value, locale, derivedAt) ) // Pins are the filtered events that have coordinates; virtual events stay in diff --git a/apps/website/src/templates/events/PastEventsSection.test.ts b/apps/website/src/templates/events/PastEventsSection.test.ts index 8461fe0555d..476745d5339 100644 --- a/apps/website/src/templates/events/PastEventsSection.test.ts +++ b/apps/website/src/templates/events/PastEventsSection.test.ts @@ -1,11 +1,10 @@ // @vitest-environment happy-dom import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import { nextTick } from 'vue' import type { ComfyEvent } from '../../data/events' -import type * as eventsModule from '../../data/events' import PastEventsSection from './PastEventsSection.vue' @@ -14,7 +13,7 @@ import PastEventsSection from './PastEventsSection.vue' // art, an unrecorded workshop with no art whose only destination is its // external page, an untranslated conference, and a destinationless meetup with // neither a recording nor a link. -const { fixturePastEvents } = vi.hoisted(() => { +const { fixturePastEvents } = (() => { const localized = (en: string) => ({ en, 'zh-CN': en }) const recorded: ComfyEvent = { id: 'recorded-livestream', @@ -77,16 +76,11 @@ const { fixturePastEvents } = vi.hoisted(() => { return { fixturePastEvents: [recorded, clip, artless, untranslated, destinationless] } -}) - -vi.mock(import('../../data/events'), async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, pastEvents: fixturePastEvents } -}) +})() describe('PastEventsSection', () => { it('renders a card for every past event, artless ones included', () => { - render(PastEventsSection) + render(PastEventsSection, { props: { events: fixturePastEvents } }) expect(screen.getByText('Recorded Livestream')).toBeTruthy() expect(screen.getByText('Clip Meetup')).toBeTruthy() @@ -94,7 +88,7 @@ describe('PastEventsSection', () => { }) it('sends a recorded event to its own page under a WATCH NOW label', () => { - render(PastEventsSection) + render(PastEventsSection, { props: { events: fixturePastEvents } }) const link = screen.getByRole('link', { name: 'Recorded Livestream — WATCH NOW' @@ -104,7 +98,7 @@ describe('PastEventsSection', () => { }) it('links an unrecorded event out under LEARN MORE in a new tab', () => { - render(PastEventsSection) + render(PastEventsSection, { props: { events: fixturePastEvents } }) const link = screen.getByRole('link', { name: 'Artless Workshop — LEARN MORE' @@ -114,7 +108,9 @@ describe('PastEventsSection', () => { }) it('falls back to English title, art alt, and link for untranslated events', () => { - render(PastEventsSection, { props: { locale: 'zh-CN' } }) + render(PastEventsSection, { + props: { locale: 'zh-CN', events: fixturePastEvents } + }) const link = screen.getByRole('link', { name: 'English-Only Conference — 了解更多' @@ -124,7 +120,7 @@ describe('PastEventsSection', () => { }) it('offers a filter tab only for categories that have a card', () => { - render(PastEventsSection) + render(PastEventsSection, { props: { events: fixturePastEvents } }) expect(screen.getByRole('button', { name: /^ALL \d+$/ })).toBeTruthy() expect( @@ -138,7 +134,7 @@ describe('PastEventsSection', () => { }) it('narrows the cards to a tab category and restores them via ALL', async () => { - render(PastEventsSection) + render(PastEventsSection, { props: { events: fixturePastEvents } }) await userEvent.click( screen.getByRole('button', { name: /^WORKSHOP \d+$/ }) @@ -160,7 +156,7 @@ describe('PastEventsSection', () => { }) it('holds the overflowing card behind LOAD MORE and gives it no CTA', async () => { - render(PastEventsSection) + render(PastEventsSection, { props: { events: fixturePastEvents } }) // PAST_EVENTS_PAGE_SIZE is 4, so the fifth fixture waits behind the button. expect(screen.queryByText('Destinationless Meetup')).toBeNull() @@ -177,7 +173,9 @@ describe('PastEventsSection', () => { }) it('passes each card its own art, poster included for clips', () => { - const { container } = render(PastEventsSection) + const { container } = render(PastEventsSection, { + props: { events: fixturePastEvents } + }) expect( screen.getByRole('img', { name: 'Livestream art' }).getAttribute('src') diff --git a/apps/website/src/templates/events/PastEventsSection.vue b/apps/website/src/templates/events/PastEventsSection.vue index c4b97e3e0c3..85a93ea90c9 100644 --- a/apps/website/src/templates/events/PastEventsSection.vue +++ b/apps/website/src/templates/events/PastEventsSection.vue @@ -1,6 +1,7 @@