Line data Source code
1 : import { createSharedComposable } from '@vueuse/core'
2 :
3 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
4 : import { reportError } from '@comfyorg/telemetry/reportError'
5 :
6 : interface CanvasOperationBase {
7 : element?: HTMLCanvasElement
8 : run: () => void
9 : }
10 :
11 : type CanvasOperation =
12 : | (CanvasOperationBase & { key?: never; isCurrent?: never })
13 : | (CanvasOperationBase & { key: string; isCurrent: () => boolean })
14 :
15 : export interface CanvasScheduler {
16 : /** Run an op now when its canvas is visible, otherwise queue it. */
17 : schedule(operation: CanvasOperation): void
18 : /** Run every queued op whose canvas is now visible; keep the rest queued. */
19 : flush(): void
20 : /** Discard the pending operation with this key. */
21 : cancel(key: string): void
22 : }
23 :
24 2355 : export function createCanvasScheduler(): CanvasScheduler {
25 2355 : const canvasStore = useCanvasStore()
26 2355 : const queue: CanvasOperation[] = []
27 :
28 7849 : function targetOf(operation: CanvasOperation): HTMLCanvasElement | undefined {
29 7849 : return operation.element ?? canvasStore.canvas?.canvas
30 : }
31 :
32 7849 : function isVisible(element: HTMLCanvasElement | undefined): boolean {
33 7849 : return (
34 : element?.offsetParent != null &&
35 : element.offsetWidth > 0 &&
36 : element.offsetHeight > 0
37 : )
38 : }
39 :
40 3924 : function isStale(operation: CanvasOperation): boolean {
41 3924 : if (operation.isCurrent?.() === false) return true
42 3924 : const { element } = operation
43 3924 : return Boolean(
44 : element && element !== canvasStore.canvas?.canvas && !element.isConnected
45 : )
46 : }
47 :
48 3924 : function run(operation: CanvasOperation): void {
49 3924 : try {
50 3924 : operation.run()
51 : } catch (error) {
52 0 : reportError(error, {
53 : errorType: 'canvas_scheduled_operation_failed',
54 : surface: 'graph'
55 : })
56 : }
57 : }
58 :
59 6454 : function flush(): void {
60 6454 : for (const operation of queue.splice(0)) {
61 3924 : if (isStale(operation)) continue
62 3924 : if (isVisible(targetOf(operation))) run(operation)
63 0 : else queue.push(operation)
64 : }
65 : }
66 :
67 3925 : function schedule(operation: CanvasOperation): void {
68 3925 : if (operation.isCurrent?.() === false) return
69 :
70 3925 : const existingIndex = operation.key
71 : ? queue.findIndex(({ key }) => key === operation.key)
72 : : -1
73 3925 : if (existingIndex === -1) queue.push(operation)
74 0 : else queue[existingIndex] = operation
75 :
76 3925 : if (isVisible(targetOf(operation))) flush()
77 : }
78 :
79 4097 : function cancel(key: string): void {
80 4097 : const index = queue.findIndex((operation) => operation.key === key)
81 4097 : if (index !== -1) queue.splice(index, 1)
82 : }
83 :
84 2355 : return { schedule, flush, cancel }
85 : }
86 :
87 2356 : export const useCanvasScheduler = createSharedComposable(createCanvasScheduler)
|