Line data Source code
1 : import { useChainCallback } from '@/composables/functional/useChainCallback'
2 : import { partition } from 'es-toolkit'
3 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
4 :
5 : interface FileInputOptions {
6 : accept?: string
7 : allow_batch?: boolean
8 : fileFilter?: (file: File) => boolean
9 : onReject?: (files: File[]) => void
10 : onSelect: (files: File[]) => void
11 : }
12 :
13 : /**
14 : * Creates a file input for a node.
15 : */
16 260 : export function useNodeFileInput(node: LGraphNode, options: FileInputOptions) {
17 260 : const {
18 : accept,
19 : allow_batch = false,
20 : fileFilter = () => true,
21 : onSelect
22 : } = options
23 :
24 260 : let fileInput: HTMLInputElement | null = document.createElement('input')
25 260 : fileInput.type = 'file'
26 260 : fileInput.accept = accept ?? '*'
27 260 : fileInput.multiple = allow_batch
28 :
29 260 : fileInput.onchange = () => {
30 3 : const selectedFiles = fileInput?.files?.length
31 : ? Array.from(fileInput.files)
32 : : []
33 3 : const [files, rejectedFiles] = partition(selectedFiles, fileFilter)
34 : // Reset value so re-selecting the same file triggers onchange
35 3 : if (fileInput) fileInput.value = ''
36 3 : if (rejectedFiles.length) options.onReject?.(rejectedFiles)
37 3 : if (files.length) onSelect(files)
38 : }
39 :
40 260 : node.onRemoved = useChainCallback(node.onRemoved, () => {
41 35 : if (fileInput) {
42 35 : fileInput.onchange = null
43 35 : fileInput = null
44 : }
45 : })
46 :
47 260 : return {
48 : openFileSelection: () => fileInput?.click()
49 : }
50 : }
|