mirror of
https://github.com/Comfy-Org/ComfyUI_frontend.git
synced 2026-07-16 08:49:09 +00:00
Compare commits
36 Commits
v1.33.2
...
cloud/fix-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b3b389e1d | ||
|
|
58b051a473 | ||
|
|
0b33470744 | ||
|
|
fb3ce74d2f | ||
|
|
86d3f0ebd5 | ||
|
|
09c888e338 | ||
|
|
6d41e8b6e4 | ||
|
|
274f77869b | ||
|
|
f5c9f69678 | ||
|
|
c1e237255a | ||
|
|
a91b9f288f | ||
|
|
4adcf09cca | ||
|
|
1dbb3fc1b9 | ||
|
|
d6c5b33fce | ||
|
|
f5608435b4 | ||
|
|
9da82f47ef | ||
|
|
a8d6f7baff | ||
|
|
a7daa5071c | ||
|
|
639975b804 | ||
|
|
ff0d385db8 | ||
|
|
6e2e591937 | ||
|
|
27fcc4554f | ||
|
|
e563c1be75 | ||
|
|
5a297e520c | ||
|
|
85bec5ee47 | ||
|
|
bdf6d4dea2 | ||
|
|
b8a796212c | ||
|
|
bc553f12be | ||
|
|
6bb35d46c1 | ||
|
|
68c38f0098 | ||
|
|
236247f05f | ||
|
|
87d6d18c57 | ||
|
|
87106ccb95 | ||
|
|
a20fb7d260 | ||
|
|
836cd7f9ba | ||
|
|
acd855601c |
3
.github/workflows/pr-backport.yaml
vendored
3
.github/workflows/pr-backport.yaml
vendored
@@ -78,8 +78,7 @@ jobs:
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
LABELS=$(gh pr view ${{ inputs.pr_number }} --json labels | jq -r '.labels[].name')
|
||||
else
|
||||
LABELS='${{ toJSON(github.event.pull_request.labels) }}'
|
||||
LABELS=$(echo "$LABELS" | jq -r '.[].name')
|
||||
LABELS=$(jq -r '.pull_request.labels[].name' "$GITHUB_EVENT_PATH")
|
||||
fi
|
||||
|
||||
add_target() {
|
||||
|
||||
@@ -557,7 +557,7 @@ export class ComfyPage {
|
||||
async dragAndDrop(source: Position, target: Position) {
|
||||
await this.page.mouse.move(source.x, source.y)
|
||||
await this.page.mouse.down()
|
||||
await this.page.mouse.move(target.x, target.y)
|
||||
await this.page.mouse.move(target.x, target.y, { steps: 100 })
|
||||
await this.page.mouse.up()
|
||||
await this.nextFrame()
|
||||
}
|
||||
|
||||
@@ -65,7 +65,9 @@ export class VueNodeHelpers {
|
||||
* Select a specific Vue node by ID
|
||||
*/
|
||||
async selectNode(nodeId: string): Promise<void> {
|
||||
await this.page.locator(`[data-node-id="${nodeId}"]`).click()
|
||||
await this.page
|
||||
.locator(`[data-node-id="${nodeId}"] .lg-node-header`)
|
||||
.click()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,11 +79,13 @@ export class VueNodeHelpers {
|
||||
// Select first node normally
|
||||
await this.selectNode(nodeIds[0])
|
||||
|
||||
// Add additional nodes with Ctrl+click
|
||||
// Add additional nodes with Ctrl+click on header
|
||||
for (let i = 1; i < nodeIds.length; i++) {
|
||||
await this.page.locator(`[data-node-id="${nodeIds[i]}"]`).click({
|
||||
modifiers: ['Control']
|
||||
})
|
||||
await this.page
|
||||
.locator(`[data-node-id="${nodeIds[i]}"] .lg-node-header`)
|
||||
.click({
|
||||
modifiers: ['Control']
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 99 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 97 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 55 KiB |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@comfyorg/comfyui-frontend",
|
||||
"private": true,
|
||||
"version": "1.33.2",
|
||||
"version": "1.33.7",
|
||||
"type": "module",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"homepage": "https://comfy.org",
|
||||
@@ -75,6 +75,7 @@
|
||||
"@vitest/coverage-v8": "catalog:",
|
||||
"@vitest/ui": "catalog:",
|
||||
"@vue/test-utils": "catalog:",
|
||||
"@webgpu/types": "catalog:",
|
||||
"cross-env": "catalog:",
|
||||
"eslint": "catalog:",
|
||||
"eslint-config-prettier": "catalog:",
|
||||
@@ -112,6 +113,7 @@
|
||||
"typescript": "catalog:",
|
||||
"typescript-eslint": "catalog:",
|
||||
"unplugin-icons": "catalog:",
|
||||
"unplugin-typegpu": "catalog:",
|
||||
"unplugin-vue-components": "catalog:",
|
||||
"uuid": "^11.1.0",
|
||||
"vite": "catalog:",
|
||||
@@ -176,6 +178,7 @@
|
||||
"semver": "^7.7.2",
|
||||
"three": "^0.170.0",
|
||||
"tiptap-markdown": "^0.8.10",
|
||||
"typegpu": "catalog:",
|
||||
"vue": "catalog:",
|
||||
"vue-i18n": "catalog:",
|
||||
"vue-router": "catalog:",
|
||||
|
||||
86
pnpm-lock.yaml
generated
86
pnpm-lock.yaml
generated
@@ -126,6 +126,9 @@ catalogs:
|
||||
'@vueuse/integrations':
|
||||
specifier: ^13.9.0
|
||||
version: 13.9.0
|
||||
'@webgpu/types':
|
||||
specifier: ^0.1.66
|
||||
version: 0.1.66
|
||||
algoliasearch:
|
||||
specifier: ^5.21.0
|
||||
version: 5.21.0
|
||||
@@ -246,6 +249,9 @@ catalogs:
|
||||
tw-animate-css:
|
||||
specifier: ^1.3.8
|
||||
version: 1.3.8
|
||||
typegpu:
|
||||
specifier: ^0.8.2
|
||||
version: 0.8.2
|
||||
typescript:
|
||||
specifier: ^5.9.2
|
||||
version: 5.9.2
|
||||
@@ -255,6 +261,9 @@ catalogs:
|
||||
unplugin-icons:
|
||||
specifier: ^0.22.0
|
||||
version: 0.22.0
|
||||
unplugin-typegpu:
|
||||
specifier: 0.8.0
|
||||
version: 0.8.0
|
||||
unplugin-vue-components:
|
||||
specifier: ^0.28.0
|
||||
version: 0.28.0
|
||||
@@ -464,6 +473,9 @@ importers:
|
||||
tiptap-markdown:
|
||||
specifier: ^0.8.10
|
||||
version: 0.8.10(@tiptap/core@2.10.4(@tiptap/pm@2.10.4))
|
||||
typegpu:
|
||||
specifier: 'catalog:'
|
||||
version: 0.8.2
|
||||
vue:
|
||||
specifier: 'catalog:'
|
||||
version: 3.5.13(typescript@5.9.2)
|
||||
@@ -561,6 +573,9 @@ importers:
|
||||
'@vue/test-utils':
|
||||
specifier: 'catalog:'
|
||||
version: 2.4.6
|
||||
'@webgpu/types':
|
||||
specifier: 'catalog:'
|
||||
version: 0.1.66
|
||||
cross-env:
|
||||
specifier: 'catalog:'
|
||||
version: 10.1.0
|
||||
@@ -672,6 +687,9 @@ importers:
|
||||
unplugin-icons:
|
||||
specifier: 'catalog:'
|
||||
version: 0.22.0(@vue/compiler-sfc@3.5.13)
|
||||
unplugin-typegpu:
|
||||
specifier: 'catalog:'
|
||||
version: 0.8.0(typegpu@0.8.2)
|
||||
unplugin-vue-components:
|
||||
specifier: 'catalog:'
|
||||
version: 0.28.0(@babel/parser@7.28.4)(rollup@4.22.4)(vue@3.5.13(typescript@5.9.2))
|
||||
@@ -1431,6 +1449,10 @@ packages:
|
||||
resolution: {integrity: sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/standalone@7.28.5':
|
||||
resolution: {integrity: sha512-1DViPYJpRU50irpGMfLBQ9B4kyfQuL6X7SS7pwTeWeZX0mNkjzPi0XFqxCjSdddZXUQy4AhnQnnesA/ZHnvAdw==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/template@7.27.2':
|
||||
resolution: {integrity: sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
@@ -3790,8 +3812,8 @@ packages:
|
||||
peerDependencies:
|
||||
vue: ^3.5.0
|
||||
|
||||
'@webgpu/types@0.1.51':
|
||||
resolution: {integrity: sha512-ktR3u64NPjwIViNCck+z9QeyN0iPkQCUOQ07ZCV1RzlkfP+olLTeEZ95O1QHS+v4w9vJeY9xj/uJuSphsHy5rQ==}
|
||||
'@webgpu/types@0.1.66':
|
||||
resolution: {integrity: sha512-YA2hLrwLpDsRueNDXIMqN9NTzD6bCDkuXbOSe0heS+f8YE8usA6Gbv1prj81pzVHrbaAma7zObnIC+I6/sXJgA==}
|
||||
|
||||
'@xstate/fsm@1.6.5':
|
||||
resolution: {integrity: sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==}
|
||||
@@ -6038,6 +6060,10 @@ packages:
|
||||
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
|
||||
hasBin: true
|
||||
|
||||
magic-string-ast@1.0.3:
|
||||
resolution: {integrity: sha512-CvkkH1i81zl7mmb94DsRiFeG9V2fR2JeuK8yDgS8oiZSFa++wWLEgZ5ufEOyLHbvSbD1gTRKv9NdX69Rnvr9JA==}
|
||||
engines: {node: '>=20.19.0'}
|
||||
|
||||
magic-string@0.30.19:
|
||||
resolution: {integrity: sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw==}
|
||||
|
||||
@@ -7411,6 +7437,14 @@ packages:
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
tinyest-for-wgsl@0.1.3:
|
||||
resolution: {integrity: sha512-Wm5ADG1UyDxykf42S1gLYP4U9e1QP/TdtJeovQi6y68zttpiFLKqQGioHmPs9Mjysh7YMSAr/Lpuk0cD2MVdGA==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
tinyest@0.1.2:
|
||||
resolution: {integrity: sha512-aHRmouyowIq1P5jrTF+YK6pGX+WuvFtSCLbqk91yHnU3SWQRIcNIamZLM5XF6lLqB13AWz0PGPXRff2QGDsxIg==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
tinyexec@0.3.2:
|
||||
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
|
||||
|
||||
@@ -7537,6 +7571,13 @@ packages:
|
||||
resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
typed-binary@4.3.2:
|
||||
resolution: {integrity: sha512-HT3pIBM2njCZUmeczDaQUUErGiM6GXFCqMsHegE12HCoBtvHCkfR10JJni0TeGOTnLilTd6YFyj+YhflqQDrDQ==}
|
||||
|
||||
typegpu@0.8.2:
|
||||
resolution: {integrity: sha512-wkMJWhJE0pSkw2G/FesjqjbtHkREyOKu1Zmyj19xfmaX5+65YFwgfQNKSK8CxqN4kJkP7JFelLDJTSYY536TYg==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
typescript-eslint@8.44.0:
|
||||
resolution: {integrity: sha512-ib7mCkYuIzYonCq9XWF5XNw+fkj2zg629PSa9KNIQ47RXFF763S5BIX4wqz1+FLPogTZoiw8KmCiRPRa8bL3qw==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@@ -7641,6 +7682,11 @@ packages:
|
||||
vue-template-es2015-compiler:
|
||||
optional: true
|
||||
|
||||
unplugin-typegpu@0.8.0:
|
||||
resolution: {integrity: sha512-VJHdXSXGOkAx0WhwFczhVUjAI6HyDkrQXk20HnwyuzIE3FdqE5l9sJTCYZzoVGo3z8i/IA5TMHCDzzP0Bc97Cw==}
|
||||
peerDependencies:
|
||||
typegpu: ^0.8.0
|
||||
|
||||
unplugin-vue-components@0.28.0:
|
||||
resolution: {integrity: sha512-jiTGtJ3JsRFBjgvyilfrX7yUoGKScFgbdNw+6p6kEXU+Spf/rhxzgvdfuMcvhCcLmflB/dY3pGQshYBVGOUx7Q==}
|
||||
engines: {node: '>=14'}
|
||||
@@ -8969,6 +9015,8 @@ snapshots:
|
||||
|
||||
'@babel/runtime@7.28.4': {}
|
||||
|
||||
'@babel/standalone@7.28.5': {}
|
||||
|
||||
'@babel/template@7.27.2':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.27.1
|
||||
@@ -11016,7 +11064,7 @@ snapshots:
|
||||
'@tweenjs/tween.js': 23.1.3
|
||||
'@types/stats.js': 0.17.3
|
||||
'@types/webxr': 0.5.20
|
||||
'@webgpu/types': 0.1.51
|
||||
'@webgpu/types': 0.1.66
|
||||
fflate: 0.8.2
|
||||
meshoptimizer: 0.18.1
|
||||
|
||||
@@ -11519,7 +11567,7 @@ snapshots:
|
||||
dependencies:
|
||||
vue: 3.5.13(typescript@5.9.2)
|
||||
|
||||
'@webgpu/types@0.1.51': {}
|
||||
'@webgpu/types@0.1.66': {}
|
||||
|
||||
'@xstate/fsm@1.6.5': {}
|
||||
|
||||
@@ -14000,6 +14048,10 @@ snapshots:
|
||||
|
||||
lz-string@1.5.0: {}
|
||||
|
||||
magic-string-ast@1.0.3:
|
||||
dependencies:
|
||||
magic-string: 0.30.19
|
||||
|
||||
magic-string@0.30.19:
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
@@ -15864,6 +15916,12 @@ snapshots:
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyest-for-wgsl@0.1.3:
|
||||
dependencies:
|
||||
tinyest: 0.1.2
|
||||
|
||||
tinyest@0.1.2: {}
|
||||
|
||||
tinyexec@0.3.2: {}
|
||||
|
||||
tinyexec@1.0.1: {}
|
||||
@@ -15995,6 +16053,13 @@ snapshots:
|
||||
reflect.getprototypeof: 1.0.10
|
||||
optional: true
|
||||
|
||||
typed-binary@4.3.2: {}
|
||||
|
||||
typegpu@0.8.2:
|
||||
dependencies:
|
||||
tinyest: 0.1.2
|
||||
typed-binary: 4.3.2
|
||||
|
||||
typescript-eslint@8.44.0(eslint@9.35.0(jiti@2.4.2))(typescript@5.9.2):
|
||||
dependencies:
|
||||
'@typescript-eslint/eslint-plugin': 8.44.0(@typescript-eslint/parser@8.44.0(eslint@9.35.0(jiti@2.4.2))(typescript@5.9.2))(eslint@9.35.0(jiti@2.4.2))(typescript@5.9.2)
|
||||
@@ -16090,6 +16155,19 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
unplugin-typegpu@0.8.0(typegpu@0.8.2):
|
||||
dependencies:
|
||||
'@babel/standalone': 7.28.5
|
||||
defu: 6.1.4
|
||||
estree-walker: 3.0.3
|
||||
magic-string-ast: 1.0.3
|
||||
pathe: 2.0.3
|
||||
picomatch: 4.0.3
|
||||
tinyest: 0.1.2
|
||||
tinyest-for-wgsl: 0.1.3
|
||||
typegpu: 0.8.2
|
||||
unplugin: 2.3.5
|
||||
|
||||
unplugin-vue-components@0.28.0(@babel/parser@7.28.4)(rollup@4.22.4)(vue@3.5.13(typescript@5.9.2)):
|
||||
dependencies:
|
||||
'@antfu/utils': 0.7.10
|
||||
|
||||
@@ -43,6 +43,7 @@ catalog:
|
||||
'@vue/test-utils': ^2.4.6
|
||||
'@vueuse/core': ^11.0.0
|
||||
'@vueuse/integrations': ^13.9.0
|
||||
'@webgpu/types': ^0.1.66
|
||||
algoliasearch: ^5.21.0
|
||||
axios: ^1.8.2
|
||||
cross-env: ^10.1.0
|
||||
@@ -83,9 +84,11 @@ catalog:
|
||||
tailwindcss-primeui: ^0.6.1
|
||||
tsx: ^4.15.6
|
||||
tw-animate-css: ^1.3.8
|
||||
typegpu: ^0.8.2
|
||||
typescript: ^5.9.2
|
||||
typescript-eslint: ^8.44.0
|
||||
unplugin-icons: ^0.22.0
|
||||
unplugin-typegpu: 0.8.0
|
||||
unplugin-vue-components: ^0.28.0
|
||||
vite: ^5.4.19
|
||||
vite-plugin-dts: ^4.5.4
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
severity="primary"
|
||||
size="small"
|
||||
:model="queueModeMenuItems"
|
||||
:disabled="hasMissingNodes"
|
||||
data-testid="queue-button"
|
||||
@click="queuePrompt"
|
||||
>
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
import { cn } from '@/utils/tailwindUtil'
|
||||
|
||||
interface IconButtonProps extends BaseButtonProps {
|
||||
onClick: (event: Event) => void
|
||||
onClick?: (event: MouseEvent) => void
|
||||
}
|
||||
|
||||
defineOptions({
|
||||
|
||||
@@ -47,7 +47,7 @@ const {
|
||||
} = defineProps<IconTextButtonProps>()
|
||||
|
||||
const buttonStyle = computed(() => {
|
||||
const baseClasses = `${getBaseButtonClasses()} justify-start! gap-2`
|
||||
const baseClasses = `${getBaseButtonClasses()} justify-start gap-2`
|
||||
const sizeClasses = getButtonSizeClasses(size)
|
||||
const typeClasses = border
|
||||
? getBorderButtonTypeClasses(type)
|
||||
|
||||
@@ -68,4 +68,8 @@ const toggle = (event: Event) => {
|
||||
const hide = () => {
|
||||
popover.value?.hide()
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
hide
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -92,7 +92,7 @@
|
||||
class="w-62.5"
|
||||
>
|
||||
<template #icon>
|
||||
<i class="icon-[lucide--arrow-up-down]" />
|
||||
<i class="icon-[lucide--arrow-up-down] text-muted-foreground" />
|
||||
</template>
|
||||
</SingleSelect>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<div
|
||||
class="flex w-[490px] flex-col border-t-1 border-b-1 border-border-default"
|
||||
class="flex w-[490px] flex-col border-t-1 border-border-default"
|
||||
:class="isCloud ? 'border-b-1' : ''"
|
||||
>
|
||||
<div class="flex h-full w-full flex-col gap-4 p-4">
|
||||
<!-- Description -->
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<InputText
|
||||
ref="inputRef"
|
||||
v-model="inputValue"
|
||||
:placeholder
|
||||
autofocus
|
||||
@keyup.enter="onConfirm"
|
||||
@focus="selectAllText"
|
||||
@@ -28,6 +29,7 @@ const props = defineProps<{
|
||||
message: string
|
||||
defaultValue: string
|
||||
onConfirm: (value: string) => void
|
||||
placeholder?: string
|
||||
}>()
|
||||
|
||||
const inputValue = ref<string>(props.defaultValue)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
root: ({ props }: MultiSelectPassThroughMethodOptions) => ({
|
||||
class: cn(
|
||||
'h-10 relative inline-flex cursor-pointer select-none',
|
||||
'rounded-lg bg-base-background text-base-foreground',
|
||||
'rounded-lg bg-secondary-background text-base-foreground',
|
||||
'transition-all duration-200 ease-in-out',
|
||||
'border-[2.5px] border-solid',
|
||||
selectedCount > 0
|
||||
@@ -127,7 +127,7 @@
|
||||
|
||||
<!-- Trigger value (keep text scale identical) -->
|
||||
<template #value>
|
||||
<span class="text-sm text-muted-foreground">
|
||||
<span class="text-sm">
|
||||
{{ label }}
|
||||
</span>
|
||||
<span
|
||||
@@ -140,7 +140,7 @@
|
||||
|
||||
<!-- Chevron size identical to current -->
|
||||
<template #dropdownicon>
|
||||
<i class="icon-[lucide--chevron-down] text-lg text-neutral-400" />
|
||||
<i class="icon-[lucide--chevron-down] text-muted-foreground" />
|
||||
</template>
|
||||
|
||||
<!-- Custom option row: square checkbox + label (unchanged layout/colors) -->
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div :class="wrapperStyle" @click="focusInput">
|
||||
<i class="icon-[lucide--search] text-muted" />
|
||||
<i class="icon-[lucide--search] text-muted-foreground" />
|
||||
<InputText
|
||||
ref="input"
|
||||
v-model="internalSearchQuery"
|
||||
@@ -73,7 +73,7 @@ onMounted(() => autofocus && focusInput())
|
||||
|
||||
const wrapperStyle = computed(() => {
|
||||
const baseClasses =
|
||||
'relative flex w-full items-center gap-2 bg-base-background cursor-text'
|
||||
'relative flex w-full items-center gap-2 bg-secondary-background cursor-text'
|
||||
|
||||
if (showBorder) {
|
||||
return cn(
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
'h-10 relative inline-flex cursor-pointer select-none items-center',
|
||||
// trigger surface
|
||||
'rounded-lg',
|
||||
'bg-base-background text-base-foreground',
|
||||
'bg-secondary-background text-base-foreground',
|
||||
'border-[2.5px] border-solid border-transparent',
|
||||
'transition-all duration-200 ease-in-out',
|
||||
'focus-within:border-node-component-border',
|
||||
@@ -84,7 +84,7 @@
|
||||
>
|
||||
<!-- Trigger value -->
|
||||
<template #value="slotProps">
|
||||
<div class="flex items-center gap-2 text-sm text-neutral-500">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<slot name="icon" />
|
||||
<span
|
||||
v-if="slotProps.value !== null && slotProps.value !== undefined"
|
||||
@@ -100,7 +100,7 @@
|
||||
|
||||
<!-- Trigger caret -->
|
||||
<template #dropdownicon>
|
||||
<i class="icon-[lucide--chevron-down] text-base text-neutral-500" />
|
||||
<i class="icon-[lucide--chevron-down] text-muted-foreground" />
|
||||
</template>
|
||||
|
||||
<!-- Option row -->
|
||||
|
||||
@@ -26,6 +26,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import {
|
||||
getEffectiveBrushSize,
|
||||
getEffectiveHardness
|
||||
} from '@/composables/maskeditor/brushUtils'
|
||||
import { BrushShape } from '@/extensions/core/maskeditor/types'
|
||||
import { useMaskEditorStore } from '@/stores/maskEditorStore'
|
||||
|
||||
@@ -36,11 +40,14 @@ const { containerRef } = defineProps<{
|
||||
const store = useMaskEditorStore()
|
||||
|
||||
const brushOpacity = computed(() => {
|
||||
return store.brushVisible ? '1' : '0'
|
||||
return store.brushVisible ? 1 : 0
|
||||
})
|
||||
|
||||
const brushRadius = computed(() => {
|
||||
return store.brushSettings.size * store.zoomRatio
|
||||
const size = store.brushSettings.size
|
||||
const hardness = store.brushSettings.hardness
|
||||
const effectiveSize = getEffectiveBrushSize(size, hardness)
|
||||
return effectiveSize * store.zoomRatio
|
||||
})
|
||||
|
||||
const brushSize = computed(() => {
|
||||
@@ -78,19 +85,26 @@ const gradientVisible = computed(() => {
|
||||
})
|
||||
|
||||
const gradientBackground = computed(() => {
|
||||
const size = store.brushSettings.size
|
||||
const hardness = store.brushSettings.hardness
|
||||
const effectiveSize = getEffectiveBrushSize(size, hardness)
|
||||
const effectiveHardness = getEffectiveHardness(size, hardness, effectiveSize)
|
||||
|
||||
if (hardness === 1) {
|
||||
if (effectiveHardness === 1) {
|
||||
return 'rgba(255, 0, 0, 0.5)'
|
||||
}
|
||||
|
||||
const midStop = hardness * 100
|
||||
const midStop = effectiveHardness * 100
|
||||
const outerStop = 100
|
||||
// Add an intermediate stop to approximate the squared falloff
|
||||
// At 50% of the fade region, squared falloff is 0.25 (relative to max)
|
||||
const fadeMidStop = midStop + (outerStop - midStop) * 0.5
|
||||
|
||||
return `radial-gradient(
|
||||
circle,
|
||||
rgba(255, 0, 0, 0.5) 0%,
|
||||
rgba(255, 0, 0, 0.25) ${midStop}%,
|
||||
rgba(255, 0, 0, 0.5) ${midStop}%,
|
||||
rgba(255, 0, 0, 0.125) ${fadeMidStop}%,
|
||||
rgba(255, 0, 0, 0) ${outerStop}%
|
||||
)`
|
||||
})
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
<SliderControl
|
||||
:label="t('maskEditor.thickness')"
|
||||
:min="1"
|
||||
:max="100"
|
||||
:max="500"
|
||||
:step="1"
|
||||
:model-value="store.brushSettings.size"
|
||||
@update:model-value="onThicknessChange"
|
||||
@@ -80,12 +80,12 @@
|
||||
/>
|
||||
|
||||
<SliderControl
|
||||
:label="t('maskEditor.smoothingPrecision')"
|
||||
label="Stepsize"
|
||||
:min="1"
|
||||
:max="100"
|
||||
:step="1"
|
||||
:model-value="store.brushSettings.smoothingPrecision"
|
||||
@update:model-value="onSmoothingPrecisionChange"
|
||||
:model-value="store.brushSettings.stepSize"
|
||||
@update:model-value="onStepSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -119,8 +119,8 @@ const onHardnessChange = (value: number) => {
|
||||
store.setBrushHardness(value)
|
||||
}
|
||||
|
||||
const onSmoothingPrecisionChange = (value: number) => {
|
||||
store.setBrushSmoothingPrecision(value)
|
||||
const onStepSizeChange = (value: number) => {
|
||||
store.setBrushStepSize(value)
|
||||
}
|
||||
|
||||
const resetToDefault = () => {
|
||||
|
||||
@@ -12,19 +12,28 @@
|
||||
>
|
||||
<canvas
|
||||
ref="imgCanvasRef"
|
||||
class="absolute top-0 left-0 w-full h-full"
|
||||
class="absolute top-0 left-0 w-full h-full z-0"
|
||||
@contextmenu.prevent
|
||||
/>
|
||||
<canvas
|
||||
ref="rgbCanvasRef"
|
||||
class="absolute top-0 left-0 w-full h-full"
|
||||
class="absolute top-0 left-0 w-full h-full z-10"
|
||||
@contextmenu.prevent
|
||||
/>
|
||||
<canvas
|
||||
ref="maskCanvasRef"
|
||||
class="absolute top-0 left-0 w-full h-full"
|
||||
class="absolute top-0 left-0 w-full h-full z-30"
|
||||
@contextmenu.prevent
|
||||
/>
|
||||
<!-- GPU Preview Canvas -->
|
||||
<canvas
|
||||
ref="gpuCanvasRef"
|
||||
class="absolute top-0 left-0 w-full h-full pointer-events-none"
|
||||
:class="{
|
||||
'z-20': store.activeLayer === 'rgb',
|
||||
'z-40': store.activeLayer === 'mask'
|
||||
}"
|
||||
/>
|
||||
<div ref="canvasBackgroundRef" class="bg-white w-full h-full" />
|
||||
</div>
|
||||
|
||||
@@ -87,6 +96,7 @@ const canvasContainerRef = ref<HTMLDivElement>()
|
||||
const imgCanvasRef = ref<HTMLCanvasElement>()
|
||||
const maskCanvasRef = ref<HTMLCanvasElement>()
|
||||
const rgbCanvasRef = ref<HTMLCanvasElement>()
|
||||
const gpuCanvasRef = ref<HTMLCanvasElement>()
|
||||
const canvasBackgroundRef = ref<HTMLDivElement>()
|
||||
|
||||
const toolPanelRef = ref<InstanceType<typeof ToolPanel>>()
|
||||
@@ -97,7 +107,7 @@ const initialized = ref(false)
|
||||
const keyboard = useKeyboard()
|
||||
const panZoom = usePanAndZoom()
|
||||
|
||||
let toolManager: ReturnType<typeof useToolManager> | null = null
|
||||
const toolManager = useToolManager(keyboard, panZoom)
|
||||
|
||||
let resizeObserver: ResizeObserver | null = null
|
||||
|
||||
@@ -135,8 +145,6 @@ const initUI = async () => {
|
||||
try {
|
||||
await loader.loadFromNode(node)
|
||||
|
||||
toolManager = useToolManager(keyboard, panZoom)
|
||||
|
||||
const imageLoader = useImageLoader()
|
||||
const image = await imageLoader.loadImages()
|
||||
|
||||
@@ -149,6 +157,18 @@ const initUI = async () => {
|
||||
|
||||
store.canvasHistory.saveInitialState()
|
||||
|
||||
// Initialize GPU resources
|
||||
if (toolManager.brushDrawing) {
|
||||
await toolManager.brushDrawing.initGPUResources()
|
||||
if (gpuCanvasRef.value && toolManager.brushDrawing.initPreviewCanvas) {
|
||||
// Match preview canvas resolution to mask canvas
|
||||
gpuCanvasRef.value.width = maskCanvasRef.value.width
|
||||
gpuCanvasRef.value.height = maskCanvasRef.value.height
|
||||
|
||||
toolManager.brushDrawing.initPreviewCanvas(gpuCanvasRef.value)
|
||||
}
|
||||
}
|
||||
|
||||
initialized.value = true
|
||||
} catch (error) {
|
||||
console.error('[MaskEditorContent] Initialization failed:', error)
|
||||
@@ -172,7 +192,7 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
toolManager?.brushDrawing.saveBrushSettings()
|
||||
toolManager.brushDrawing.saveBrushSettings()
|
||||
|
||||
keyboard?.removeListeners()
|
||||
|
||||
|
||||
@@ -102,6 +102,7 @@ const onInvert = () => {
|
||||
|
||||
const onClear = () => {
|
||||
canvasTools.clearMask()
|
||||
store.triggerClear()
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ https://github.com/Nuked88/ComfyUI-N-Sidebar/blob/7ae7da4a9761009fb6629bc04c6830
|
||||
-->
|
||||
<template>
|
||||
<LGraphNodePreview v-if="shouldRenderVueNodes" :node-def="nodeDef" />
|
||||
<div v-else class="_sb_node_preview">
|
||||
<div v-else class="_sb_node_preview bg-component-node-background">
|
||||
<div class="_sb_table">
|
||||
<div
|
||||
class="node_header mr-4 text-ellipsis"
|
||||
@@ -200,7 +200,6 @@ const truncateDefaultValue = (value: any, charLimit: number = 32): string => {
|
||||
}
|
||||
|
||||
._sb_node_preview {
|
||||
background-color: var(--comfy-menu-bg);
|
||||
font-family: 'Open Sans', sans-serif;
|
||||
color: var(--descrip-text);
|
||||
border: 1px solid var(--descrip-text);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
class="group flex w-full items-center justify-between gap-3 rounded-lg border-0 bg-secondary-background p-1 text-left transition-colors duration-200 ease-in-out hover:cursor-pointer hover:bg-secondary-background-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-background"
|
||||
<IconButton
|
||||
type="secondary"
|
||||
size="fit-content"
|
||||
class="group w-full justify-between gap-3 rounded-lg p-1 text-left font-normal hover:cursor-pointer focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-background"
|
||||
:aria-label="props.ariaLabel"
|
||||
@click="emit('click', $event)"
|
||||
>
|
||||
<span class="inline-flex items-center gap-2">
|
||||
<span v-if="props.mode === 'allFailed'" class="inline-flex items-center">
|
||||
@@ -76,10 +78,11 @@
|
||||
>
|
||||
<i class="icon-[lucide--chevron-down] block size-4 leading-none" />
|
||||
</span>
|
||||
</button>
|
||||
</IconButton>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import type {
|
||||
CompletionSummary,
|
||||
CompletionSummaryMode
|
||||
@@ -96,4 +99,8 @@ type Props = {
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
thumbnailUrls: () => []
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'click', event: MouseEvent): void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
@@ -42,17 +42,19 @@
|
||||
t('sideToolbar.queueProgressOverlay.running')
|
||||
}}</span>
|
||||
</span>
|
||||
<button
|
||||
<IconButton
|
||||
v-if="runningCount > 0"
|
||||
v-tooltip.top="cancelJobTooltip"
|
||||
class="inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-secondary-background p-0 transition-colors hover:bg-destructive-background"
|
||||
type="secondary"
|
||||
size="sm"
|
||||
class="size-6 bg-secondary-background hover:bg-destructive-background"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.interruptAll')"
|
||||
@click="$emit('interruptAll')"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--x] block size-4 leading-none text-text-primary"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
@@ -62,26 +64,28 @@
|
||||
t('sideToolbar.queueProgressOverlay.queuedSuffix')
|
||||
}}</span>
|
||||
</span>
|
||||
<button
|
||||
<IconButton
|
||||
v-if="queuedCount > 0"
|
||||
v-tooltip.top="clearQueueTooltip"
|
||||
class="inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-secondary-background p-0 transition-colors hover:bg-destructive-background"
|
||||
type="secondary"
|
||||
size="sm"
|
||||
class="size-6 bg-secondary-background hover:bg-destructive-background"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.clearQueued')"
|
||||
@click="$emit('clearQueued')"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--list-x] block size-4 leading-none text-text-primary"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
class="inline-flex h-6 min-w-[120px] flex-1 cursor-pointer items-center justify-center rounded border-0 bg-secondary-background px-2 py-0 text-[12px] text-text-primary hover:bg-secondary-background-hover hover:opacity-90"
|
||||
<TextButton
|
||||
class="h-6 min-w-[120px] flex-1 px-2 py-0 text-[12px]"
|
||||
type="secondary"
|
||||
:label="t('sideToolbar.queueProgressOverlay.viewAllJobs')"
|
||||
@click="$emit('viewAllJobs')"
|
||||
>
|
||||
{{ t('sideToolbar.queueProgressOverlay.viewAllJobs') }}
|
||||
</button>
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -90,6 +94,8 @@
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import TextButton from '@/components/button/TextButton.vue'
|
||||
import { buildTooltipConfig } from '@/composables/useTooltipConfig'
|
||||
|
||||
defineProps<{
|
||||
|
||||
@@ -8,17 +8,20 @@
|
||||
/>
|
||||
|
||||
<div class="flex items-center justify-between px-3">
|
||||
<button
|
||||
class="inline-flex grow cursor-pointer items-center justify-center gap-1 rounded border-0 bg-secondary-background p-2 text-center font-inter text-[12px] leading-none text-text-primary hover:bg-secondary-background-hover hover:opacity-90"
|
||||
<IconTextButton
|
||||
class="grow gap-1 p-2 text-center font-inter text-[12px] leading-none hover:opacity-90 justify-center"
|
||||
type="secondary"
|
||||
:label="t('sideToolbar.queueProgressOverlay.showAssets')"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.showAssets')"
|
||||
@click="$emit('showAssets')"
|
||||
>
|
||||
<div
|
||||
class="pointer-events-none block size-4 shrink-0 leading-none icon-[comfy--image-ai-edit]"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>{{ t('sideToolbar.queueProgressOverlay.showAssets') }}</span>
|
||||
</button>
|
||||
<template #icon>
|
||||
<div
|
||||
class="pointer-events-none block size-4 shrink-0 leading-none icon-[comfy--image-ai-edit]"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
<div class="ml-4 inline-flex items-center">
|
||||
<div
|
||||
class="inline-flex h-6 items-center text-[12px] leading-none text-text-primary opacity-90"
|
||||
@@ -28,16 +31,18 @@
|
||||
t('sideToolbar.queueProgressOverlay.queuedSuffix')
|
||||
}}</span>
|
||||
</div>
|
||||
<button
|
||||
<IconButton
|
||||
v-if="queuedCount > 0"
|
||||
class="group ml-2 inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-secondary-background p-0 transition-colors hover:bg-destructive-background"
|
||||
class="group ml-2 size-6 bg-secondary-background hover:bg-destructive-background"
|
||||
type="secondary"
|
||||
size="sm"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.clearQueued')"
|
||||
@click="$emit('clearQueued')"
|
||||
>
|
||||
<i
|
||||
class="pointer-events-none icon-[lucide--list-x] block size-4 leading-none text-text-primary transition-colors group-hover:text-base-background"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -75,6 +80,8 @@
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import IconTextButton from '@/components/button/IconTextButton.vue'
|
||||
import type {
|
||||
JobGroup,
|
||||
JobListItem,
|
||||
|
||||
@@ -18,16 +18,18 @@
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
<IconButton
|
||||
v-tooltip.top="moreTooltipConfig"
|
||||
class="inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-transparent p-0 hover:bg-secondary-background hover:opacity-100"
|
||||
type="transparent"
|
||||
size="sm"
|
||||
class="size-6 bg-transparent hover:bg-secondary-background hover:opacity-100"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.moreOptions')"
|
||||
@click="onMoreClick"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--more-horizontal] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
<Popover
|
||||
ref="morePopoverRef"
|
||||
:dismissable="true"
|
||||
@@ -45,18 +47,19 @@
|
||||
<div
|
||||
class="flex flex-col items-stretch rounded-lg border border-interface-stroke bg-interface-panel-surface px-2 py-3 font-inter"
|
||||
>
|
||||
<button
|
||||
class="inline-flex w-full cursor-pointer items-center justify-start gap-2 rounded-lg border-0 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
<IconTextButton
|
||||
class="w-full justify-start gap-2 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
type="transparent"
|
||||
:label="t('sideToolbar.queueProgressOverlay.clearHistory')"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.clearHistory')"
|
||||
@click="onClearHistoryFromMenu"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--file-x-2] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
<span>{{
|
||||
t('sideToolbar.queueProgressOverlay.clearHistory')
|
||||
}}</span>
|
||||
</button>
|
||||
<template #icon>
|
||||
<i
|
||||
class="icon-[lucide--file-x-2] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
</div>
|
||||
</Popover>
|
||||
</div>
|
||||
@@ -69,6 +72,8 @@ import type { PopoverMethods } from 'primevue/popover'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import IconTextButton from '@/components/button/IconTextButton.vue'
|
||||
import { buildTooltipConfig } from '@/composables/useTooltipConfig'
|
||||
|
||||
defineProps<{
|
||||
|
||||
@@ -8,13 +8,15 @@
|
||||
<p class="m-0 text-[14px] font-normal leading-none">
|
||||
{{ t('sideToolbar.queueProgressOverlay.clearHistoryDialogTitle') }}
|
||||
</p>
|
||||
<button
|
||||
class="inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-transparent p-0 text-text-secondary transition hover:bg-secondary-background hover:opacity-100"
|
||||
<IconButton
|
||||
type="transparent"
|
||||
size="sm"
|
||||
class="size-6 bg-transparent text-text-secondary hover:bg-secondary-background hover:opacity-100"
|
||||
:aria-label="t('g.close')"
|
||||
@click="onCancel"
|
||||
>
|
||||
<i class="icon-[lucide--x] block size-4 leading-none" />
|
||||
</button>
|
||||
</IconButton>
|
||||
</header>
|
||||
|
||||
<div class="flex flex-col gap-4 px-4 py-4 text-[14px] text-text-secondary">
|
||||
@@ -30,21 +32,19 @@
|
||||
|
||||
<footer class="flex items-center justify-end px-4 py-4">
|
||||
<div class="flex items-center gap-4 text-[14px] leading-none">
|
||||
<button
|
||||
class="inline-flex min-h-[24px] cursor-pointer items-center rounded-md border-0 bg-transparent px-1 py-1 text-[14px] leading-[1] text-text-secondary transition hover:text-text-primary"
|
||||
:aria-label="t('g.cancel')"
|
||||
<TextButton
|
||||
class="min-h-[24px] px-1 py-1 text-[14px] leading-[1] text-text-secondary hover:text-text-primary"
|
||||
type="transparent"
|
||||
:label="t('g.cancel')"
|
||||
@click="onCancel"
|
||||
>
|
||||
{{ t('g.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
class="inline-flex min-h-[32px] items-center rounded-lg border-0 bg-secondary-background px-4 py-2 text-[12px] font-normal leading-[1] text-text-primary transition hover:bg-secondary-background-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:aria-label="t('g.clear')"
|
||||
/>
|
||||
<TextButton
|
||||
class="min-h-[32px] px-4 py-2 text-[12px] font-normal leading-[1]"
|
||||
type="secondary"
|
||||
:label="t('g.clear')"
|
||||
:disabled="isClearing"
|
||||
@click="onConfirm"
|
||||
>
|
||||
{{ t('g.clear') }}
|
||||
</button>
|
||||
/>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
@@ -54,6 +54,8 @@
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import TextButton from '@/components/button/TextButton.vue'
|
||||
import { useErrorHandling } from '@/composables/useErrorHandling'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
import { useQueueStore } from '@/stores/queueStore'
|
||||
|
||||
@@ -20,21 +20,24 @@
|
||||
<div v-if="entry.kind === 'divider'" class="px-2 py-1">
|
||||
<div class="h-px bg-interface-stroke" />
|
||||
</div>
|
||||
<button
|
||||
<IconTextButton
|
||||
v-else
|
||||
class="inline-flex w-full cursor-pointer items-center justify-start gap-2 rounded-lg border-0 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary transition-colors duration-150 hover:bg-interface-panel-hover-surface"
|
||||
class="w-full justify-start gap-2 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-interface-panel-hover-surface"
|
||||
type="transparent"
|
||||
:label="entry.label"
|
||||
:aria-label="entry.label"
|
||||
@click="onEntry(entry)"
|
||||
>
|
||||
<i
|
||||
v-if="entry.icon"
|
||||
:class="[
|
||||
entry.icon,
|
||||
'block size-4 shrink-0 leading-none text-text-secondary'
|
||||
]"
|
||||
/>
|
||||
<span>{{ entry.label }}</span>
|
||||
</button>
|
||||
<template #icon>
|
||||
<i
|
||||
v-if="entry.icon"
|
||||
:class="[
|
||||
entry.icon,
|
||||
'block size-4 shrink-0 leading-none text-text-secondary'
|
||||
]"
|
||||
/>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
</template>
|
||||
</div>
|
||||
</Popover>
|
||||
@@ -44,6 +47,7 @@
|
||||
import Popover from 'primevue/popover'
|
||||
import { ref } from 'vue'
|
||||
|
||||
import IconTextButton from '@/components/button/IconTextButton.vue'
|
||||
import type { MenuEntry } from '@/composables/queue/useJobMenu'
|
||||
|
||||
defineProps<{ entries: MenuEntry[] }>()
|
||||
|
||||
@@ -20,17 +20,18 @@
|
||||
class="flex min-w-0 items-center text-[0.75rem] leading-normal font-normal text-text-secondary"
|
||||
>
|
||||
<span class="block min-w-0 truncate">{{ row.value }}</span>
|
||||
<button
|
||||
<IconButton
|
||||
v-if="row.canCopy"
|
||||
type="button"
|
||||
class="ml-2 inline-flex size-6 items-center justify-center rounded border-0 bg-transparent p-0 hover:opacity-90"
|
||||
type="transparent"
|
||||
size="sm"
|
||||
class="ml-2 size-6 bg-transparent hover:opacity-90"
|
||||
:aria-label="copyAriaLabel"
|
||||
@click.stop="copyJobId"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--copy] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -60,25 +61,31 @@
|
||||
{{ t('queue.jobDetails.errorMessage') }}
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-6 items-center justify-center gap-2 rounded border-none bg-transparent px-0 text-[0.75rem] leading-none text-text-secondary hover:opacity-90"
|
||||
<IconTextButton
|
||||
class="h-6 justify-start gap-2 bg-transparent px-0 text-[0.75rem] leading-none text-text-secondary hover:opacity-90"
|
||||
type="transparent"
|
||||
:label="copyAriaLabel"
|
||||
:aria-label="copyAriaLabel"
|
||||
icon-position="right"
|
||||
@click.stop="copyErrorMessage"
|
||||
>
|
||||
<span>{{ copyAriaLabel }}</span>
|
||||
<i class="icon-[lucide--copy] block size-3.5 leading-none" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-6 items-center justify-center gap-2 rounded border-none bg-transparent px-0 text-[0.75rem] leading-none text-text-secondary hover:opacity-90"
|
||||
<template #icon>
|
||||
<i class="icon-[lucide--copy] block size-3.5 leading-none" />
|
||||
</template>
|
||||
</IconTextButton>
|
||||
<IconTextButton
|
||||
class="h-6 justify-start gap-2 bg-transparent px-0 text-[0.75rem] leading-none text-text-secondary hover:opacity-90"
|
||||
type="transparent"
|
||||
:label="t('queue.jobDetails.report')"
|
||||
icon-position="right"
|
||||
@click.stop="reportJobError"
|
||||
>
|
||||
<span>{{ t('queue.jobDetails.report') }}</span>
|
||||
<i
|
||||
class="icon-[lucide--message-circle-warning] block size-3.5 leading-none"
|
||||
/>
|
||||
</button>
|
||||
<template #icon>
|
||||
<i
|
||||
class="icon-[lucide--message-circle-warning] block size-3.5 leading-none"
|
||||
/>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
</div>
|
||||
<div
|
||||
class="col-span-2 mt-2 rounded bg-interface-panel-hover-surface px-4 py-2 text-[0.75rem] leading-normal text-text-secondary"
|
||||
@@ -94,6 +101,8 @@
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import IconTextButton from '@/components/button/IconTextButton.vue'
|
||||
import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
|
||||
import { t } from '@/i18n'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
|
||||
@@ -2,26 +2,26 @@
|
||||
<div class="flex items-center justify-between gap-2 px-3">
|
||||
<div class="min-w-0 flex-1 overflow-x-auto">
|
||||
<div class="inline-flex items-center gap-1 whitespace-nowrap">
|
||||
<button
|
||||
<TextButton
|
||||
v-for="tab in visibleJobTabs"
|
||||
:key="tab"
|
||||
class="h-6 cursor-pointer rounded border-0 px-3 py-1 text-[12px] leading-none hover:opacity-90"
|
||||
class="h-6 px-3 py-1 text-[12px] leading-none hover:opacity-90"
|
||||
:type="selectedJobTab === tab ? 'secondary' : 'transparent'"
|
||||
:class="[
|
||||
selectedJobTab === tab
|
||||
? 'bg-secondary-background text-text-primary'
|
||||
: 'bg-transparent text-text-secondary'
|
||||
selectedJobTab === tab ? 'text-text-primary' : 'text-text-secondary'
|
||||
]"
|
||||
:label="tabLabel(tab)"
|
||||
@click="$emit('update:selectedJobTab', tab)"
|
||||
>
|
||||
{{ tabLabel(tab) }}
|
||||
</button>
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ml-2 flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
<IconButton
|
||||
v-if="showWorkflowFilter"
|
||||
v-tooltip.top="filterTooltipConfig"
|
||||
class="relative inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-secondary-background p-0 hover:bg-secondary-background-hover hover:opacity-90"
|
||||
type="secondary"
|
||||
size="sm"
|
||||
class="relative size-6 bg-secondary-background hover:bg-secondary-background-hover hover:opacity-90"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.filterJobs')"
|
||||
@click="onFilterClick"
|
||||
>
|
||||
@@ -32,7 +32,7 @@
|
||||
v-if="selectedWorkflowFilter !== 'all'"
|
||||
class="pointer-events-none absolute -top-1 -right-1 inline-block size-2 rounded-full bg-base-foreground"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
<Popover
|
||||
v-if="showWorkflowFilter"
|
||||
ref="filterPopoverRef"
|
||||
@@ -51,46 +51,48 @@
|
||||
<div
|
||||
class="flex min-w-[12rem] flex-col items-stretch rounded-lg border border-interface-stroke bg-interface-panel-surface px-2 py-3"
|
||||
>
|
||||
<button
|
||||
class="inline-flex w-full cursor-pointer items-center justify-start gap-1 rounded-lg border-0 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
<IconTextButton
|
||||
class="w-full justify-between gap-1 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
type="transparent"
|
||||
icon-position="right"
|
||||
:label="t('sideToolbar.queueProgressOverlay.filterAllWorkflows')"
|
||||
:aria-label="
|
||||
t('sideToolbar.queueProgressOverlay.filterAllWorkflows')
|
||||
"
|
||||
@click="selectWorkflowFilter('all')"
|
||||
>
|
||||
<span>{{
|
||||
t('sideToolbar.queueProgressOverlay.filterAllWorkflows')
|
||||
}}</span>
|
||||
<span class="ml-auto inline-flex items-center">
|
||||
<template #icon>
|
||||
<i
|
||||
v-if="selectedWorkflowFilter === 'all'"
|
||||
class="icon-[lucide--check] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
<div class="mx-2 mt-1 h-px" />
|
||||
<button
|
||||
class="inline-flex w-full cursor-pointer items-center justify-start gap-1 rounded-lg border-0 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
<IconTextButton
|
||||
class="w-full justify-between gap-1 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
type="transparent"
|
||||
icon-position="right"
|
||||
:label="t('sideToolbar.queueProgressOverlay.filterCurrentWorkflow')"
|
||||
:aria-label="
|
||||
t('sideToolbar.queueProgressOverlay.filterCurrentWorkflow')
|
||||
"
|
||||
@click="selectWorkflowFilter('current')"
|
||||
>
|
||||
<span>{{
|
||||
t('sideToolbar.queueProgressOverlay.filterCurrentWorkflow')
|
||||
}}</span>
|
||||
<span class="ml-auto inline-flex items-center">
|
||||
<template #icon>
|
||||
<i
|
||||
v-if="selectedWorkflowFilter === 'current'"
|
||||
class="icon-[lucide--check] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
</div>
|
||||
</Popover>
|
||||
<button
|
||||
<IconButton
|
||||
v-tooltip.top="sortTooltipConfig"
|
||||
class="relative inline-flex size-6 cursor-pointer items-center justify-center rounded border-0 bg-secondary-background p-0 hover:bg-secondary-background-hover hover:opacity-90"
|
||||
type="secondary"
|
||||
size="sm"
|
||||
class="relative size-6 bg-secondary-background hover:bg-secondary-background-hover hover:opacity-90"
|
||||
:aria-label="t('sideToolbar.queueProgressOverlay.sortJobs')"
|
||||
@click="onSortClick"
|
||||
>
|
||||
@@ -101,7 +103,7 @@
|
||||
v-if="selectedSortMode !== 'mostRecent'"
|
||||
class="pointer-events-none absolute -top-1 -right-1 inline-block size-2 rounded-full bg-base-foreground"
|
||||
/>
|
||||
</button>
|
||||
</IconButton>
|
||||
<Popover
|
||||
ref="sortPopoverRef"
|
||||
:dismissable="true"
|
||||
@@ -120,19 +122,21 @@
|
||||
class="flex min-w-[12rem] flex-col items-stretch rounded-lg border border-interface-stroke bg-interface-panel-surface px-2 py-3"
|
||||
>
|
||||
<template v-for="(mode, index) in jobSortModes" :key="mode">
|
||||
<button
|
||||
class="inline-flex w-full cursor-pointer items-center justify-start gap-1 rounded-lg border-0 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
<IconTextButton
|
||||
class="w-full justify-between gap-1 bg-transparent p-2 font-inter text-[12px] leading-none text-text-primary hover:bg-transparent hover:opacity-90"
|
||||
type="transparent"
|
||||
icon-position="right"
|
||||
:label="sortLabel(mode)"
|
||||
:aria-label="sortLabel(mode)"
|
||||
@click="selectSortMode(mode)"
|
||||
>
|
||||
<span>{{ sortLabel(mode) }}</span>
|
||||
<span class="ml-auto inline-flex items-center">
|
||||
<template #icon>
|
||||
<i
|
||||
v-if="selectedSortMode === mode"
|
||||
class="icon-[lucide--check] block size-4 leading-none text-text-secondary"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
<div
|
||||
v-if="index < jobSortModes.length - 1"
|
||||
class="mx-2 mt-1 h-px"
|
||||
@@ -149,6 +153,9 @@ import Popover from 'primevue/popover'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import IconTextButton from '@/components/button/IconTextButton.vue'
|
||||
import TextButton from '@/components/button/TextButton.vue'
|
||||
import { jobSortModes, jobTabs } from '@/composables/queue/useJobList'
|
||||
import type { JobSortMode, JobTab } from '@/composables/queue/useJobList'
|
||||
import { buildTooltipConfig } from '@/composables/useTooltipConfig'
|
||||
|
||||
@@ -108,45 +108,47 @@
|
||||
key="actions"
|
||||
class="inline-flex items-center gap-2 pr-1"
|
||||
>
|
||||
<button
|
||||
<IconButton
|
||||
v-if="props.state === 'failed' && computedShowClear"
|
||||
v-tooltip.top="deleteTooltipConfig"
|
||||
type="button"
|
||||
class="inline-flex h-6 transform cursor-pointer items-center gap-1 rounded border-0 bg-modal-card-button-surface px-1 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:bg-destructive-background hover:opacity-95"
|
||||
type="transparent"
|
||||
size="sm"
|
||||
class="h-6 transform gap-1 rounded bg-modal-card-button-surface px-1 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:bg-destructive-background hover:opacity-95"
|
||||
:aria-label="t('g.delete')"
|
||||
@click.stop="emit('delete')"
|
||||
>
|
||||
<i class="icon-[lucide--trash-2] size-4" />
|
||||
</button>
|
||||
<button
|
||||
</IconButton>
|
||||
<IconButton
|
||||
v-else-if="props.state !== 'completed' && computedShowClear"
|
||||
v-tooltip.top="cancelTooltipConfig"
|
||||
type="button"
|
||||
class="inline-flex h-6 transform cursor-pointer items-center gap-1 rounded border-0 bg-modal-card-button-surface px-1 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:bg-destructive-background hover:opacity-95"
|
||||
type="transparent"
|
||||
size="sm"
|
||||
class="h-6 transform gap-1 rounded bg-modal-card-button-surface px-1 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:bg-destructive-background hover:opacity-95"
|
||||
:aria-label="t('g.cancel')"
|
||||
@click.stop="emit('cancel')"
|
||||
>
|
||||
<i class="icon-[lucide--x] size-4" />
|
||||
</button>
|
||||
<button
|
||||
</IconButton>
|
||||
<TextButton
|
||||
v-else-if="props.state === 'completed'"
|
||||
type="button"
|
||||
class="inline-flex h-6 transform cursor-pointer items-center gap-1 rounded border-0 bg-modal-card-button-surface px-2 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:opacity-95"
|
||||
class="h-6 transform gap-1 rounded bg-modal-card-button-surface px-2 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:opacity-95"
|
||||
type="transparent"
|
||||
:label="t('menuLabels.View')"
|
||||
:aria-label="t('menuLabels.View')"
|
||||
@click.stop="emit('view')"
|
||||
>
|
||||
<span>{{ t('menuLabels.View') }}</span>
|
||||
</button>
|
||||
<button
|
||||
/>
|
||||
<IconButton
|
||||
v-if="props.showMenu !== undefined ? props.showMenu : true"
|
||||
v-tooltip.top="moreTooltipConfig"
|
||||
type="button"
|
||||
class="inline-flex h-6 transform cursor-pointer items-center gap-1 rounded border-0 bg-modal-card-button-surface px-1 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:opacity-95"
|
||||
type="transparent"
|
||||
size="sm"
|
||||
class="h-6 transform gap-1 rounded bg-modal-card-button-surface px-1 py-0 text-text-primary transition duration-150 ease-in-out hover:-translate-y-px hover:opacity-95"
|
||||
:aria-label="t('g.more')"
|
||||
@click.stop="emit('menu', $event)"
|
||||
>
|
||||
<i class="icon-[lucide--more-horizontal] size-4" />
|
||||
</button>
|
||||
</IconButton>
|
||||
</div>
|
||||
<div v-else key="secondary" class="pr-2">
|
||||
<slot name="secondary">{{ props.rightText }}</slot>
|
||||
@@ -161,6 +163,8 @@
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
import TextButton from '@/components/button/TextButton.vue'
|
||||
import JobDetailsPopover from '@/components/queue/job/JobDetailsPopover.vue'
|
||||
import QueueAssetPreview from '@/components/queue/job/QueueAssetPreview.vue'
|
||||
import { buildTooltipConfig } from '@/composables/useTooltipConfig'
|
||||
|
||||
@@ -85,10 +85,13 @@
|
||||
:show-output-count="shouldShowOutputCount(item)"
|
||||
:output-count="getOutputCount(item)"
|
||||
:show-delete-button="shouldShowDeleteButton"
|
||||
:open-popover-id="openPopoverId"
|
||||
@click="handleAssetSelect(item)"
|
||||
@zoom="handleZoomClick(item)"
|
||||
@output-count-click="enterFolderView(item)"
|
||||
@asset-deleted="refreshAssets"
|
||||
@popover-opened="openPopoverId = item.id"
|
||||
@popover-closed="openPopoverId = null"
|
||||
/>
|
||||
</template>
|
||||
</VirtualGrid>
|
||||
@@ -199,6 +202,9 @@ const folderPromptId = ref<string | null>(null)
|
||||
const folderExecutionTime = ref<number | undefined>(undefined)
|
||||
const isInFolderView = computed(() => folderPromptId.value !== null)
|
||||
|
||||
// Track which asset's popover is open (for single-instance popover management)
|
||||
const openPopoverId = ref<string | null>(null)
|
||||
|
||||
// Determine if delete button should be shown
|
||||
// Hide delete button when in input tab and not in cloud (OSS mode - files are from local folders)
|
||||
const shouldShowDeleteButton = computed(() => {
|
||||
@@ -208,7 +214,7 @@ const shouldShowDeleteButton = computed(() => {
|
||||
|
||||
const getOutputCount = (item: AssetItem): number => {
|
||||
const count = item.user_metadata?.outputCount
|
||||
return typeof count === 'number' && count > 0 ? count : 0
|
||||
return typeof count === 'number' && count > 0 ? count : 1
|
||||
}
|
||||
|
||||
const shouldShowOutputCount = (item: AssetItem): boolean => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations'
|
||||
import { LayoutSource } from '@/renderer/core/layout/types'
|
||||
import type { NodeId } from '@/renderer/core/layout/types'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { isDOMWidget } from '@/scripts/domWidget'
|
||||
import { useNodeDefStore } from '@/stores/nodeDefStore'
|
||||
@@ -46,7 +47,7 @@ export interface SafeWidgetData {
|
||||
}
|
||||
|
||||
export interface VueNodeData {
|
||||
id: string
|
||||
id: NodeId
|
||||
title: string
|
||||
type: string
|
||||
mode: number
|
||||
|
||||
84
src/composables/maskeditor/ShiftClick.test.ts
Normal file
84
src/composables/maskeditor/ShiftClick.test.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { resampleSegment } from './splineUtils'
|
||||
import type { Point } from '@/extensions/core/maskeditor/types'
|
||||
|
||||
describe('Shift+Click Drawing Logic', () => {
|
||||
it('should generate equidistant points across connected segments', () => {
|
||||
const spacing = 4
|
||||
let remainder = spacing // Simulate start point already painted
|
||||
const outputPoints: Point[] = []
|
||||
|
||||
// Define points: A -> B -> C
|
||||
// A(0,0) -> B(10,0) -> C(20,0)
|
||||
// Total length 20. Spacing 4.
|
||||
// Expected points at x = 4, 8, 12, 16, 20
|
||||
const pA = { x: 0, y: 0 }
|
||||
const pB = { x: 10, y: 0 }
|
||||
const pC = { x: 20, y: 0 }
|
||||
|
||||
// Segment 1: A -> B
|
||||
const result1 = resampleSegment([pA, pB], spacing, remainder)
|
||||
outputPoints.push(...result1.points)
|
||||
remainder = result1.remainder
|
||||
|
||||
// Verify intermediate state
|
||||
// Length 10. Spacing 4. Start offset 4.
|
||||
// Points at 4, 8. Next at 12.
|
||||
// Remainder = 12 - 10 = 2.
|
||||
expect(result1.points.length).toBe(2)
|
||||
expect(result1.points[0].x).toBeCloseTo(4)
|
||||
expect(result1.points[1].x).toBeCloseTo(8)
|
||||
expect(remainder).toBeCloseTo(2)
|
||||
|
||||
// Segment 2: B -> C
|
||||
const result2 = resampleSegment([pB, pC], spacing, remainder)
|
||||
outputPoints.push(...result2.points)
|
||||
remainder = result2.remainder
|
||||
|
||||
// Verify final state
|
||||
// Start offset 2. Points at 2, 6, 10 (relative to B).
|
||||
// Absolute x: 12, 16, 20.
|
||||
expect(result2.points.length).toBe(3)
|
||||
expect(result2.points[0].x).toBeCloseTo(12)
|
||||
expect(result2.points[1].x).toBeCloseTo(16)
|
||||
expect(result2.points[2].x).toBeCloseTo(20)
|
||||
|
||||
// Verify all distances
|
||||
// Note: The first point is at distance `spacing` from start (0,0)
|
||||
// Subsequent points are `spacing` apart.
|
||||
let prevX = 0
|
||||
for (const p of outputPoints) {
|
||||
const dist = p.x - prevX
|
||||
expect(dist).toBeCloseTo(spacing)
|
||||
prevX = p.x
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle segments shorter than spacing', () => {
|
||||
const spacing = 10
|
||||
let remainder = spacing // Simulate start point already painted
|
||||
|
||||
// A(0,0) -> B(5,0) -> C(15,0)
|
||||
const pA = { x: 0, y: 0 }
|
||||
const pB = { x: 5, y: 0 }
|
||||
const pC = { x: 15, y: 0 }
|
||||
|
||||
// Segment 1: A -> B (Length 5)
|
||||
// Spacing 10. No points should be generated.
|
||||
// Remainder should be 5 (next point needs 5 more units).
|
||||
const result1 = resampleSegment([pA, pB], spacing, remainder)
|
||||
expect(result1.points.length).toBe(0)
|
||||
expect(result1.remainder).toBeCloseTo(5)
|
||||
remainder = result1.remainder
|
||||
|
||||
// Segment 2: B -> C (Length 10)
|
||||
// Start offset 5. First point at 5 (relative to B).
|
||||
// Absolute x = 10.
|
||||
// Next point at 15 (relative to B). Segment ends at 10.
|
||||
// Remainder = 15 - 10 = 5.
|
||||
const result2 = resampleSegment([pB, pC], spacing, remainder)
|
||||
expect(result2.points.length).toBe(1)
|
||||
expect(result2.points[0].x).toBeCloseTo(10)
|
||||
expect(result2.remainder).toBeCloseTo(5)
|
||||
})
|
||||
})
|
||||
108
src/composables/maskeditor/StrokeProcessor.test.ts
Normal file
108
src/composables/maskeditor/StrokeProcessor.test.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { StrokeProcessor } from './StrokeProcessor'
|
||||
import type { Point } from '@/extensions/core/maskeditor/types'
|
||||
|
||||
describe('StrokeProcessor', () => {
|
||||
it('should generate equidistant points from irregular input', () => {
|
||||
const spacing = 10
|
||||
const processor = new StrokeProcessor(spacing)
|
||||
const outputPoints: Point[] = []
|
||||
|
||||
// Simulate a horizontal line drawn with irregular speed
|
||||
// Points: (0,0) -> (5,0) -> (25,0) -> (30,0) -> (100,0)
|
||||
const inputPoints: Point[] = [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 5, y: 0 }, // dist 5
|
||||
{ x: 25, y: 0 }, // dist 20
|
||||
{ x: 30, y: 0 }, // dist 5
|
||||
{ x: 100, y: 0 } // dist 70
|
||||
]
|
||||
|
||||
for (const p of inputPoints) {
|
||||
outputPoints.push(...processor.addPoint(p))
|
||||
}
|
||||
outputPoints.push(...processor.endStroke())
|
||||
|
||||
// Verify we have points
|
||||
expect(outputPoints.length).toBeGreaterThan(0)
|
||||
|
||||
// Verify spacing
|
||||
// Note: The first few points might be affected by the start condition,
|
||||
// but the middle section should be perfectly spaced.
|
||||
// Also, Catmull-Rom splines don't necessarily pass through control points in a straight line
|
||||
// if the points are collinear, they should be straight.
|
||||
|
||||
// Let's check distances between consecutive points
|
||||
const distances: number[] = []
|
||||
for (let i = 1; i < outputPoints.length; i++) {
|
||||
const dx = outputPoints[i].x - outputPoints[i - 1].x
|
||||
const dy = outputPoints[i].y - outputPoints[i - 1].y
|
||||
distances.push(Math.hypot(dx, dy))
|
||||
}
|
||||
|
||||
// Check that distances are close to spacing
|
||||
// We allow a small epsilon because of floating point and spline approximation
|
||||
// Filter out the very last segment which might be shorter (remainder)
|
||||
// But wait, our logic doesn't output the last point if it's not a full spacing step?
|
||||
// resampleSegment outputs points at [start + spacing, start + 2*spacing, ...]
|
||||
// It does NOT output the end point of the segment.
|
||||
// So all distances between output points should be exactly `spacing`.
|
||||
// EXCEPT possibly if the spline curvature makes the straight-line distance slightly different
|
||||
// from the arc length. But for a straight line input, it should be exact.
|
||||
|
||||
// However, catmull-rom with collinear points IS a straight line.
|
||||
|
||||
// Let's log the distances for debugging if test fails
|
||||
// console.log('Distances:', distances)
|
||||
|
||||
// All distances should be approximately equal to spacing
|
||||
// We might have a gap between segments if the logic isn't perfect,
|
||||
// but within a segment it's guaranteed by resampleSegment.
|
||||
// The critical part is the transition between segments.
|
||||
|
||||
for (let i = 0; i < distances.length; i++) {
|
||||
const d = distances[i]
|
||||
if (Math.abs(d - spacing) > 0.5) {
|
||||
console.log(
|
||||
`Distance mismatch at index ${i}: ${d} (expected ${spacing})`
|
||||
)
|
||||
console.log(`Point ${i}:`, outputPoints[i])
|
||||
console.log(`Point ${i + 1}:`, outputPoints[i + 1])
|
||||
}
|
||||
expect(d).toBeCloseTo(spacing, 1)
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle a simple 3-point stroke', () => {
|
||||
const spacing = 5
|
||||
const processor = new StrokeProcessor(spacing)
|
||||
const points: Point[] = []
|
||||
|
||||
points.push(...processor.addPoint({ x: 0, y: 0 }))
|
||||
points.push(...processor.addPoint({ x: 10, y: 0 }))
|
||||
points.push(...processor.addPoint({ x: 20, y: 0 }))
|
||||
points.push(...processor.endStroke())
|
||||
|
||||
expect(points.length).toBeGreaterThan(0)
|
||||
|
||||
// Check distances
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
const dx = points[i].x - points[i - 1].x
|
||||
const dy = points[i].y - points[i - 1].y
|
||||
const d = Math.hypot(dx, dy)
|
||||
expect(d).toBeCloseTo(spacing, 1)
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle a single point click', () => {
|
||||
const spacing = 5
|
||||
const processor = new StrokeProcessor(spacing)
|
||||
const points: Point[] = []
|
||||
|
||||
points.push(...processor.addPoint({ x: 100, y: 100 }))
|
||||
points.push(...processor.endStroke())
|
||||
|
||||
expect(points.length).toBe(1)
|
||||
expect(points[0]).toEqual({ x: 100, y: 100 })
|
||||
})
|
||||
})
|
||||
115
src/composables/maskeditor/StrokeProcessor.ts
Normal file
115
src/composables/maskeditor/StrokeProcessor.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import type { Point } from '@/extensions/core/maskeditor/types'
|
||||
import { catmullRomSpline, resampleSegment } from './splineUtils'
|
||||
|
||||
export class StrokeProcessor {
|
||||
private controlPoints: Point[] = []
|
||||
private remainder: number = 0
|
||||
private spacing: number
|
||||
private isFirstPoint: boolean = true
|
||||
private hasProcessedSegment: boolean = false
|
||||
|
||||
constructor(spacing: number) {
|
||||
this.spacing = spacing
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a point to the stroke and returns any new equidistant points generated.
|
||||
* Maintain a sliding window of 4 control points for spline generation
|
||||
*/
|
||||
public addPoint(point: Point): Point[] {
|
||||
// Initialize buffer with the first point
|
||||
if (this.isFirstPoint) {
|
||||
this.controlPoints.push(point) // p0: phantom start point
|
||||
this.controlPoints.push(point) // p1: actual start point
|
||||
this.isFirstPoint = false
|
||||
return [] // Wait for more points to form a segment
|
||||
}
|
||||
|
||||
this.controlPoints.push(point)
|
||||
|
||||
// Require 4 points for a spline segment
|
||||
if (this.controlPoints.length < 4) {
|
||||
return []
|
||||
}
|
||||
|
||||
// Generate segment p1->p2
|
||||
const p0 = this.controlPoints[0]
|
||||
const p1 = this.controlPoints[1]
|
||||
const p2 = this.controlPoints[2]
|
||||
const p3 = this.controlPoints[3]
|
||||
|
||||
const newPoints = this.processSegment(p0, p1, p2, p3)
|
||||
|
||||
// Slide window
|
||||
this.controlPoints.shift()
|
||||
|
||||
return newPoints
|
||||
}
|
||||
|
||||
/**
|
||||
* End stroke and flush remaining segments
|
||||
*/
|
||||
public endStroke(): Point[] {
|
||||
if (this.controlPoints.length < 2) {
|
||||
// Insufficient points for a segment
|
||||
return []
|
||||
}
|
||||
|
||||
// Process remaining segments by duplicating the last point
|
||||
|
||||
const newPoints: Point[] = []
|
||||
|
||||
// Flush the buffer by processing the final segment
|
||||
|
||||
while (this.controlPoints.length >= 3) {
|
||||
const p0 = this.controlPoints[0]
|
||||
const p1 = this.controlPoints[1]
|
||||
const p2 = this.controlPoints[2]
|
||||
const p3 = p2 // Duplicate last point as phantom end
|
||||
|
||||
const points = this.processSegment(p0, p1, p2, p3)
|
||||
newPoints.push(...points)
|
||||
|
||||
this.controlPoints.shift()
|
||||
}
|
||||
|
||||
// Handle single point click
|
||||
if (!this.hasProcessedSegment && this.controlPoints.length >= 2) {
|
||||
// Process zero-length segment for single point
|
||||
const p = this.controlPoints[1]
|
||||
const points = this.processSegment(p, p, p, p)
|
||||
newPoints.push(...points)
|
||||
}
|
||||
|
||||
return newPoints
|
||||
}
|
||||
|
||||
private processSegment(p0: Point, p1: Point, p2: Point, p3: Point): Point[] {
|
||||
this.hasProcessedSegment = true
|
||||
// Generate dense points for the segment
|
||||
const densePoints: Point[] = []
|
||||
|
||||
// Adaptive sampling based on segment length
|
||||
const dist = Math.hypot(p2.x - p1.x, p2.y - p1.y)
|
||||
// Use 1 sample per pixel, but at least 5 samples to ensure smoothness for short segments
|
||||
// and cap at a reasonable maximum if needed (though not strictly necessary with density)
|
||||
const samples = Math.max(5, Math.ceil(dist))
|
||||
|
||||
for (let i = 0; i < samples; i++) {
|
||||
const t = i / samples
|
||||
densePoints.push(catmullRomSpline(p0, p1, p2, p3, t))
|
||||
}
|
||||
// Add segment end point
|
||||
densePoints.push(p2)
|
||||
|
||||
// Resample points with carried-over remainder
|
||||
const { points, remainder } = resampleSegment(
|
||||
densePoints,
|
||||
this.spacing,
|
||||
this.remainder
|
||||
)
|
||||
|
||||
this.remainder = remainder
|
||||
return points
|
||||
}
|
||||
}
|
||||
47
src/composables/maskeditor/brushUtils.test.ts
Normal file
47
src/composables/maskeditor/brushUtils.test.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getEffectiveBrushSize, getEffectiveHardness } from './brushUtils'
|
||||
|
||||
describe('brushUtils', () => {
|
||||
describe('getEffectiveBrushSize', () => {
|
||||
it('should return original size when hardness is 1.0', () => {
|
||||
const size = 100
|
||||
const hardness = 1.0
|
||||
expect(getEffectiveBrushSize(size, hardness)).toBe(100)
|
||||
})
|
||||
|
||||
it('should return 1.5x size when hardness is 0.0', () => {
|
||||
const size = 100
|
||||
const hardness = 0.0
|
||||
expect(getEffectiveBrushSize(size, hardness)).toBe(150)
|
||||
})
|
||||
|
||||
it('should interpolate linearly', () => {
|
||||
const size = 100
|
||||
const hardness = 0.5
|
||||
// Scale should be 1.0 + 0.5 * 0.5 = 1.25
|
||||
expect(getEffectiveBrushSize(size, hardness)).toBe(125)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getEffectiveHardness', () => {
|
||||
it('should return same hardness if effective size matches size', () => {
|
||||
const size = 100
|
||||
const hardness = 0.8
|
||||
const effectiveSize = 100
|
||||
expect(getEffectiveHardness(size, hardness, effectiveSize)).toBe(0.8)
|
||||
})
|
||||
|
||||
it('should scale hardness down as effective size increases', () => {
|
||||
const size = 100
|
||||
const hardness = 0.5
|
||||
// Effective size at 0.5 hardness is 125
|
||||
const effectiveSize = 125
|
||||
// Hard core radius = 50. New hardness = 50 / 125 = 0.4
|
||||
expect(getEffectiveHardness(size, hardness, effectiveSize)).toBe(0.4)
|
||||
})
|
||||
|
||||
it('should return 0 if effective size is 0', () => {
|
||||
expect(getEffectiveHardness(100, 0.5, 0)).toBe(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
34
src/composables/maskeditor/brushUtils.ts
Normal file
34
src/composables/maskeditor/brushUtils.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Calculates the effective brush size based on the base size and hardness.
|
||||
* As hardness decreases, the effective size increases to allow for a softer falloff.
|
||||
*
|
||||
* @param size - The base radius of the brush
|
||||
* @param hardness - The hardness of the brush (0.0 to 1.0)
|
||||
* @returns The effective radius of the brush
|
||||
*/
|
||||
export function getEffectiveBrushSize(size: number, hardness: number): number {
|
||||
// Scale factor for maximum softness
|
||||
const MAX_SCALE = 1.5
|
||||
const scale = 1.0 + (1.0 - hardness) * (MAX_SCALE - 1.0)
|
||||
return size * scale
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the effective hardness to maintain the visual "hard core" of the brush.
|
||||
* Since the effective size is larger, we need to adjust the hardness value so that
|
||||
* the inner hard circle remains at the same physical radius as the original size * hardness.
|
||||
*
|
||||
* @param size - The base radius of the brush
|
||||
* @param hardness - The base hardness of the brush
|
||||
* @param effectiveSize - The effective radius (calculated by getEffectiveBrushSize)
|
||||
* @returns The adjusted hardness value (0.0 to 1.0)
|
||||
*/
|
||||
export function getEffectiveHardness(
|
||||
size: number,
|
||||
hardness: number,
|
||||
effectiveSize: number
|
||||
): number {
|
||||
if (effectiveSize <= 0) return 0
|
||||
// Adjust hardness to maintain the physical radius of the hard core
|
||||
return (size * hardness) / effectiveSize
|
||||
}
|
||||
805
src/composables/maskeditor/gpu/GPUBrushRenderer.ts
Normal file
805
src/composables/maskeditor/gpu/GPUBrushRenderer.ts
Normal file
@@ -0,0 +1,805 @@
|
||||
import * as d from 'typegpu/data'
|
||||
import { StrokePoint } from './gpuSchema'
|
||||
import {
|
||||
brushFragment,
|
||||
brushVertex,
|
||||
blitShader,
|
||||
compositeShader,
|
||||
readbackShader
|
||||
} from './brushShaders'
|
||||
|
||||
// ... (rest of the file)
|
||||
|
||||
const QUAD_VERTS = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1])
|
||||
const QUAD_INDICES = new Uint16Array([0, 1, 2, 0, 2, 3])
|
||||
|
||||
const UNIFORM_SIZE = 48 // Uniform buffer size aligned to 16 bytes
|
||||
const STROKE_STRIDE = d.sizeOf(StrokePoint) // 16
|
||||
const MAX_STROKES = 10000
|
||||
|
||||
export class GPUBrushRenderer {
|
||||
private device: GPUDevice
|
||||
|
||||
// Buffers
|
||||
private quadVertexBuffer: GPUBuffer
|
||||
private indexBuffer: GPUBuffer
|
||||
private instanceBuffer: GPUBuffer
|
||||
private uniformBuffer: GPUBuffer
|
||||
|
||||
// Pipelines
|
||||
private renderPipeline: GPURenderPipeline // Standard alpha blending pipeline
|
||||
private accumulatePipeline: GPURenderPipeline // SourceOver blending pipeline for stroke accumulation
|
||||
private blitPipeline: GPURenderPipeline
|
||||
private compositePipeline: GPURenderPipeline // Composite pipeline that applies opacity
|
||||
private compositePipelinePreview: GPURenderPipeline // Pipeline for rendering to the preview canvas
|
||||
private erasePipeline: GPURenderPipeline // Pipeline for erasing (Destination Out)
|
||||
private erasePipelinePreview: GPURenderPipeline // Eraser pipeline for the preview canvas
|
||||
readbackPipeline: GPUComputePipeline // Compute pipeline for texture readback
|
||||
|
||||
// Bind Group Layouts
|
||||
private uniformBindGroupLayout: GPUBindGroupLayout
|
||||
private textureBindGroupLayout: GPUBindGroupLayout
|
||||
|
||||
// Shared Bind Groups
|
||||
private mainUniformBindGroup: GPUBindGroup
|
||||
|
||||
// Textures
|
||||
private currentStrokeTexture: GPUTexture | null = null
|
||||
private currentStrokeView: GPUTextureView | null = null
|
||||
|
||||
// Cached Bind Groups
|
||||
private compositeTextureBindGroup: GPUBindGroup | null = null
|
||||
private previewTextureBindGroup: GPUBindGroup | null = null
|
||||
|
||||
// Removed separate uniform bind groups as we will use mainUniformBindGroup
|
||||
|
||||
private lastReadbackTexture: GPUTexture | null = null
|
||||
private lastReadbackBuffer: GPUBuffer | null = null
|
||||
private readbackBindGroup: GPUBindGroup | null = null
|
||||
|
||||
private lastBackgroundTexture: GPUTexture | null = null
|
||||
private backgroundBindGroup: GPUBindGroup | null = null
|
||||
|
||||
constructor(
|
||||
device: GPUDevice,
|
||||
presentationFormat: GPUTextureFormat = 'rgba8unorm'
|
||||
) {
|
||||
this.device = device
|
||||
|
||||
// --- 1. Initialize Buffers ---
|
||||
this.quadVertexBuffer = device.createBuffer({
|
||||
size: QUAD_VERTS.byteLength,
|
||||
usage: GPUBufferUsage.VERTEX,
|
||||
mappedAtCreation: true
|
||||
})
|
||||
new Float32Array(this.quadVertexBuffer.getMappedRange()).set(QUAD_VERTS)
|
||||
this.quadVertexBuffer.unmap()
|
||||
|
||||
this.indexBuffer = device.createBuffer({
|
||||
size: QUAD_INDICES.byteLength,
|
||||
usage: GPUBufferUsage.INDEX,
|
||||
mappedAtCreation: true
|
||||
})
|
||||
new Uint16Array(this.indexBuffer.getMappedRange()).set(QUAD_INDICES)
|
||||
this.indexBuffer.unmap()
|
||||
|
||||
this.instanceBuffer = device.createBuffer({
|
||||
size: MAX_STROKES * STROKE_STRIDE,
|
||||
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
|
||||
})
|
||||
|
||||
this.uniformBuffer = device.createBuffer({
|
||||
size: UNIFORM_SIZE,
|
||||
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
|
||||
})
|
||||
|
||||
// --- 2. Brush Shader (Drawing) ---
|
||||
const brushModuleV = device.createShaderModule({ code: brushVertex })
|
||||
const brushModuleF = device.createShaderModule({ code: brushFragment })
|
||||
|
||||
// Create explicit bind group layouts
|
||||
this.uniformBindGroupLayout = device.createBindGroupLayout({
|
||||
entries: [
|
||||
{
|
||||
binding: 0,
|
||||
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
|
||||
buffer: { type: 'uniform' }
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
this.textureBindGroupLayout = device.createBindGroupLayout({
|
||||
entries: [
|
||||
{
|
||||
binding: 0,
|
||||
visibility: GPUShaderStage.FRAGMENT,
|
||||
texture: {} // default is float, 2d
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
this.mainUniformBindGroup = device.createBindGroup({
|
||||
layout: this.uniformBindGroupLayout,
|
||||
entries: [{ binding: 0, resource: { buffer: this.uniformBuffer } }]
|
||||
})
|
||||
|
||||
const renderPipelineLayout = device.createPipelineLayout({
|
||||
bindGroupLayouts: [this.uniformBindGroupLayout]
|
||||
})
|
||||
|
||||
// Standard Render Pipeline (Alpha Blend)
|
||||
this.renderPipeline = device.createRenderPipeline({
|
||||
layout: renderPipelineLayout,
|
||||
vertex: {
|
||||
module: brushModuleV,
|
||||
entryPoint: 'vs',
|
||||
buffers: [
|
||||
{
|
||||
arrayStride: 8,
|
||||
stepMode: 'vertex',
|
||||
attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }] // Quad vertex attributes
|
||||
},
|
||||
{
|
||||
arrayStride: 16,
|
||||
stepMode: 'instance',
|
||||
attributes: [
|
||||
{ shaderLocation: 1, offset: 0, format: 'float32x2' }, // Instance attributes: position
|
||||
{ shaderLocation: 2, offset: 8, format: 'float32' }, // size
|
||||
{ shaderLocation: 3, offset: 12, format: 'float32' } // pressure
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
fragment: {
|
||||
module: brushModuleF,
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: 'rgba8unorm',
|
||||
blend: {
|
||||
color: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// Accumulate strokes using SourceOver blending to ensure smooth intersections.
|
||||
this.accumulatePipeline = device.createRenderPipeline({
|
||||
layout: renderPipelineLayout,
|
||||
vertex: {
|
||||
module: brushModuleV,
|
||||
entryPoint: 'vs',
|
||||
buffers: [
|
||||
{
|
||||
arrayStride: 8,
|
||||
stepMode: 'vertex',
|
||||
attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x2' }]
|
||||
},
|
||||
{
|
||||
arrayStride: 16,
|
||||
stepMode: 'instance',
|
||||
attributes: [
|
||||
{ shaderLocation: 1, offset: 0, format: 'float32x2' },
|
||||
{ shaderLocation: 2, offset: 8, format: 'float32' },
|
||||
{ shaderLocation: 3, offset: 12, format: 'float32' }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
fragment: {
|
||||
module: brushModuleF,
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: 'rgba8unorm',
|
||||
blend: {
|
||||
// Use SourceOver blending for smooth stroke intersections.
|
||||
color: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// --- 3. Blit Pipeline (For Preview) ---
|
||||
const blitPipelineLayout = device.createPipelineLayout({
|
||||
bindGroupLayouts: [this.textureBindGroupLayout]
|
||||
})
|
||||
|
||||
this.blitPipeline = device.createRenderPipeline({
|
||||
layout: blitPipelineLayout,
|
||||
vertex: {
|
||||
module: device.createShaderModule({ code: blitShader }),
|
||||
entryPoint: 'vs'
|
||||
},
|
||||
fragment: {
|
||||
module: device.createShaderModule({ code: blitShader }),
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: presentationFormat, // Use the presentation format
|
||||
blend: {
|
||||
color: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// --- 4. Composite Pipeline ---
|
||||
|
||||
const compositePipelineLayout = device.createPipelineLayout({
|
||||
bindGroupLayouts: [
|
||||
this.textureBindGroupLayout,
|
||||
this.uniformBindGroupLayout
|
||||
]
|
||||
})
|
||||
|
||||
// Standard composite pipeline for offscreen textures
|
||||
this.compositePipeline = device.createRenderPipeline({
|
||||
layout: compositePipelineLayout,
|
||||
vertex: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'vs'
|
||||
},
|
||||
fragment: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: 'rgba8unorm',
|
||||
blend: {
|
||||
color: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// Composite pipeline for the preview canvas
|
||||
this.compositePipelinePreview = device.createRenderPipeline({
|
||||
layout: compositePipelineLayout,
|
||||
vertex: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'vs'
|
||||
},
|
||||
fragment: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: presentationFormat,
|
||||
blend: {
|
||||
color: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'one',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// --- 5. Erase Pipeline (Destination Out) ---
|
||||
// Standard erase pipeline for offscreen textures
|
||||
this.erasePipeline = device.createRenderPipeline({
|
||||
layout: compositePipelineLayout,
|
||||
vertex: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'vs'
|
||||
},
|
||||
fragment: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: 'rgba8unorm',
|
||||
blend: {
|
||||
color: {
|
||||
srcFactor: 'zero',
|
||||
dstFactor: 'one-minus-src-alpha', // dst * (1 - src_alpha)
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'zero',
|
||||
dstFactor: 'one-minus-src-alpha', // dst_alpha * (1 - src_alpha)
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// Erase pipeline for the preview canvas
|
||||
this.erasePipelinePreview = device.createRenderPipeline({
|
||||
layout: compositePipelineLayout,
|
||||
vertex: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'vs'
|
||||
},
|
||||
fragment: {
|
||||
module: device.createShaderModule({ code: compositeShader }),
|
||||
entryPoint: 'fs',
|
||||
targets: [
|
||||
{
|
||||
format: presentationFormat,
|
||||
blend: {
|
||||
color: {
|
||||
srcFactor: 'zero',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
},
|
||||
alpha: {
|
||||
srcFactor: 'zero',
|
||||
dstFactor: 'one-minus-src-alpha',
|
||||
operation: 'add'
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
primitive: { topology: 'triangle-list' }
|
||||
})
|
||||
|
||||
// --- 6. Readback Pipeline (Compute) ---
|
||||
this.readbackPipeline = device.createComputePipeline({
|
||||
layout: 'auto',
|
||||
compute: {
|
||||
module: device.createShaderModule({ code: readbackShader }),
|
||||
entryPoint: 'main'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
public prepareStroke(width: number, height: number) {
|
||||
// Initialize or resize the accumulation texture
|
||||
if (
|
||||
!this.currentStrokeTexture ||
|
||||
this.currentStrokeTexture.width !== width ||
|
||||
this.currentStrokeTexture.height !== height
|
||||
) {
|
||||
if (this.currentStrokeTexture) this.currentStrokeTexture.destroy()
|
||||
this.currentStrokeTexture = this.device.createTexture({
|
||||
size: [width, height],
|
||||
format: 'rgba8unorm',
|
||||
usage:
|
||||
GPUTextureUsage.RENDER_ATTACHMENT |
|
||||
GPUTextureUsage.TEXTURE_BINDING |
|
||||
GPUTextureUsage.COPY_SRC
|
||||
})
|
||||
this.currentStrokeView = this.currentStrokeTexture.createView()
|
||||
|
||||
// Invalidate texture-dependent bind groups
|
||||
this.compositeTextureBindGroup = null
|
||||
this.previewTextureBindGroup = null
|
||||
// Readback bind group might also be invalid if it was using the old texture
|
||||
if (this.lastReadbackTexture === this.currentStrokeTexture) {
|
||||
this.readbackBindGroup = null
|
||||
this.lastReadbackTexture = null
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the accumulation texture
|
||||
const encoder = this.device.createCommandEncoder()
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: this.currentStrokeView!,
|
||||
loadOp: 'clear',
|
||||
clearValue: { r: 0, g: 0, b: 0, a: 0 },
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
pass.end()
|
||||
this.device.queue.submit([encoder.finish()])
|
||||
}
|
||||
|
||||
public renderStrokeToAccumulator(
|
||||
points: { x: number; y: number; pressure: number }[],
|
||||
settings: {
|
||||
size: number
|
||||
opacity: number
|
||||
hardness: number
|
||||
color: [number, number, number]
|
||||
width: number
|
||||
height: number
|
||||
brushShape: number
|
||||
}
|
||||
) {
|
||||
if (!this.currentStrokeView) return
|
||||
// Render stroke using accumulation pipeline
|
||||
this.renderStrokeInternal(
|
||||
this.currentStrokeView,
|
||||
this.accumulatePipeline,
|
||||
points,
|
||||
settings
|
||||
)
|
||||
}
|
||||
|
||||
public compositeStroke(
|
||||
targetView: GPUTextureView,
|
||||
settings: {
|
||||
opacity: number
|
||||
color: [number, number, number]
|
||||
hardness: number // Required for uniform buffer layout
|
||||
screenSize: [number, number]
|
||||
brushShape: number
|
||||
isErasing?: boolean
|
||||
}
|
||||
) {
|
||||
if (!this.currentStrokeTexture) return
|
||||
|
||||
// Update uniforms for the composite pass
|
||||
const buffer = new ArrayBuffer(UNIFORM_SIZE)
|
||||
const f32 = new Float32Array(buffer)
|
||||
const u32 = new Uint32Array(buffer)
|
||||
|
||||
f32[0] = settings.color[0]
|
||||
f32[1] = settings.color[1]
|
||||
f32[2] = settings.color[2]
|
||||
f32[3] = settings.opacity
|
||||
f32[4] = settings.hardness
|
||||
f32[5] = 0 // Padding
|
||||
f32[6] = settings.screenSize[0]
|
||||
f32[7] = settings.screenSize[1]
|
||||
u32[8] = settings.brushShape // Brush shape: 0=Circle, 1=Square
|
||||
this.device.queue.writeBuffer(this.uniformBuffer, 0, buffer)
|
||||
|
||||
const encoder = this.device.createCommandEncoder()
|
||||
|
||||
// Choose pipeline based on operation
|
||||
const pipeline = settings.isErasing
|
||||
? this.erasePipeline
|
||||
: this.compositePipeline
|
||||
|
||||
// 1. Texture Bind Group (Group 0)
|
||||
if (!this.compositeTextureBindGroup) {
|
||||
this.compositeTextureBindGroup = this.device.createBindGroup({
|
||||
layout: this.textureBindGroupLayout,
|
||||
entries: [
|
||||
{ binding: 0, resource: this.currentStrokeTexture.createView() }
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Uniform Bind Group (Group 1) - Use shared mainUniformBindGroup
|
||||
// It is compatible because we used the same layout
|
||||
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: targetView,
|
||||
loadOp: 'load',
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
pass.setPipeline(pipeline)
|
||||
pass.setBindGroup(0, this.compositeTextureBindGroup)
|
||||
pass.setBindGroup(1, this.mainUniformBindGroup)
|
||||
pass.draw(3)
|
||||
pass.end()
|
||||
|
||||
this.device.queue.submit([encoder.finish()])
|
||||
}
|
||||
|
||||
// Direct rendering method
|
||||
public renderStroke(
|
||||
targetView: GPUTextureView,
|
||||
points: { x: number; y: number; pressure: number }[],
|
||||
settings: {
|
||||
size: number
|
||||
opacity: number
|
||||
hardness: number
|
||||
color: [number, number, number]
|
||||
width: number
|
||||
height: number
|
||||
brushShape: number
|
||||
}
|
||||
) {
|
||||
this.renderStrokeInternal(targetView, this.renderPipeline, points, settings)
|
||||
}
|
||||
|
||||
private renderStrokeInternal(
|
||||
targetView: GPUTextureView,
|
||||
pipeline: GPURenderPipeline,
|
||||
points: { x: number; y: number; pressure: number }[],
|
||||
settings: {
|
||||
size: number
|
||||
opacity: number
|
||||
hardness: number
|
||||
color: [number, number, number]
|
||||
width: number
|
||||
height: number
|
||||
brushShape: number
|
||||
}
|
||||
) {
|
||||
if (points.length === 0) return
|
||||
|
||||
// 1. Update Uniforms
|
||||
const buffer = new ArrayBuffer(UNIFORM_SIZE)
|
||||
const f32 = new Float32Array(buffer)
|
||||
const u32 = new Uint32Array(buffer)
|
||||
|
||||
f32[0] = settings.color[0]
|
||||
f32[1] = settings.color[1]
|
||||
f32[2] = settings.color[2]
|
||||
f32[3] = settings.opacity
|
||||
f32[4] = settings.hardness
|
||||
f32[5] = 0 // Padding
|
||||
f32[6] = settings.width
|
||||
f32[7] = settings.height
|
||||
u32[8] = settings.brushShape
|
||||
this.device.queue.writeBuffer(this.uniformBuffer, 0, buffer)
|
||||
|
||||
// 2. Batch Rendering
|
||||
let processedPoints = 0
|
||||
while (processedPoints < points.length) {
|
||||
const batchSize = Math.min(points.length - processedPoints, MAX_STROKES)
|
||||
const iData = new Float32Array(batchSize * 4)
|
||||
|
||||
for (let i = 0; i < batchSize; i++) {
|
||||
const p = points[processedPoints + i]
|
||||
iData[i * 4 + 0] = p.x
|
||||
iData[i * 4 + 1] = p.y
|
||||
iData[i * 4 + 2] = settings.size
|
||||
iData[i * 4 + 3] = p.pressure
|
||||
}
|
||||
|
||||
this.device.queue.writeBuffer(this.instanceBuffer, 0, iData)
|
||||
|
||||
// 3. Render Pass
|
||||
const encoder = this.device.createCommandEncoder()
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: targetView,
|
||||
loadOp: 'load',
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
pass.setPipeline(pipeline)
|
||||
pass.setBindGroup(0, this.mainUniformBindGroup)
|
||||
pass.setVertexBuffer(0, this.quadVertexBuffer)
|
||||
pass.setVertexBuffer(1, this.instanceBuffer)
|
||||
pass.setIndexBuffer(this.indexBuffer, 'uint16')
|
||||
pass.drawIndexed(6, batchSize)
|
||||
pass.end()
|
||||
|
||||
this.device.queue.submit([encoder.finish()])
|
||||
|
||||
processedPoints += batchSize
|
||||
}
|
||||
}
|
||||
|
||||
// Blit the accumulated stroke to the preview canvas
|
||||
public blitToCanvas(
|
||||
destinationCtx: GPUCanvasContext,
|
||||
settings: {
|
||||
opacity: number
|
||||
color: [number, number, number]
|
||||
hardness: number
|
||||
screenSize: [number, number]
|
||||
brushShape: number
|
||||
isErasing?: boolean
|
||||
},
|
||||
backgroundTexture?: GPUTexture
|
||||
) {
|
||||
const encoder = this.device.createCommandEncoder()
|
||||
const destView = destinationCtx.getCurrentTexture().createView()
|
||||
|
||||
if (backgroundTexture) {
|
||||
// Draw background texture to allow erasing effect on existing content
|
||||
if (
|
||||
this.lastBackgroundTexture !== backgroundTexture ||
|
||||
!this.backgroundBindGroup
|
||||
) {
|
||||
this.backgroundBindGroup = this.device.createBindGroup({
|
||||
layout: this.textureBindGroupLayout,
|
||||
entries: [{ binding: 0, resource: backgroundTexture.createView() }]
|
||||
})
|
||||
this.lastBackgroundTexture = backgroundTexture
|
||||
}
|
||||
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: destView,
|
||||
loadOp: 'clear', // Clear attachment before drawing
|
||||
clearValue: { r: 0, g: 0, b: 0, a: 0 },
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
pass.setPipeline(this.blitPipeline)
|
||||
pass.setBindGroup(0, this.backgroundBindGroup)
|
||||
pass.draw(3)
|
||||
pass.end()
|
||||
} else {
|
||||
// Clear the destination texture
|
||||
const clearPass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: destView,
|
||||
loadOp: 'clear',
|
||||
clearValue: { r: 0, g: 0, b: 0, a: 0 },
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
clearPass.end()
|
||||
}
|
||||
|
||||
// Draw the accumulated stroke
|
||||
if (this.currentStrokeTexture) {
|
||||
// Update uniforms for the preview pass
|
||||
const buffer = new ArrayBuffer(UNIFORM_SIZE)
|
||||
const f32 = new Float32Array(buffer)
|
||||
const u32 = new Uint32Array(buffer)
|
||||
|
||||
f32[0] = settings.color[0]
|
||||
f32[1] = settings.color[1]
|
||||
f32[2] = settings.color[2]
|
||||
f32[3] = settings.opacity
|
||||
f32[4] = settings.hardness
|
||||
f32[5] = 0 // Padding
|
||||
f32[6] = settings.screenSize[0]
|
||||
f32[7] = settings.screenSize[1]
|
||||
u32[8] = settings.brushShape
|
||||
this.device.queue.writeBuffer(this.uniformBuffer, 0, buffer)
|
||||
|
||||
// Select preview pipeline based on operation
|
||||
const pipeline = settings.isErasing
|
||||
? this.erasePipelinePreview
|
||||
: this.compositePipelinePreview
|
||||
|
||||
// 1. Texture Bind Group (Group 0)
|
||||
if (!this.previewTextureBindGroup) {
|
||||
this.previewTextureBindGroup = this.device.createBindGroup({
|
||||
layout: this.textureBindGroupLayout,
|
||||
entries: [
|
||||
{ binding: 0, resource: this.currentStrokeTexture.createView() }
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Uniform Bind Group (Group 1) - Use shared mainUniformBindGroup
|
||||
|
||||
const passStroke = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: destView,
|
||||
loadOp: 'load', // Load the previous pass result
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
passStroke.setPipeline(pipeline)
|
||||
passStroke.setBindGroup(0, this.previewTextureBindGroup)
|
||||
passStroke.setBindGroup(1, this.mainUniformBindGroup)
|
||||
passStroke.draw(3)
|
||||
passStroke.end()
|
||||
}
|
||||
|
||||
this.device.queue.submit([encoder.finish()])
|
||||
}
|
||||
|
||||
// Clear the preview canvas
|
||||
public clearPreview(destinationCtx: GPUCanvasContext) {
|
||||
const encoder = this.device.createCommandEncoder()
|
||||
const pass = encoder.beginRenderPass({
|
||||
colorAttachments: [
|
||||
{
|
||||
view: destinationCtx.getCurrentTexture().createView(),
|
||||
loadOp: 'clear',
|
||||
clearValue: { r: 0, g: 0, b: 0, a: 0 },
|
||||
storeOp: 'store'
|
||||
}
|
||||
]
|
||||
})
|
||||
pass.end()
|
||||
this.device.queue.submit([encoder.finish()])
|
||||
}
|
||||
|
||||
public prepareReadback(texture: GPUTexture, outputBuffer: GPUBuffer) {
|
||||
if (
|
||||
this.lastReadbackTexture !== texture ||
|
||||
this.lastReadbackBuffer !== outputBuffer ||
|
||||
!this.readbackBindGroup
|
||||
) {
|
||||
this.readbackBindGroup = this.device.createBindGroup({
|
||||
layout: this.readbackPipeline.getBindGroupLayout(0),
|
||||
entries: [
|
||||
{ binding: 0, resource: texture.createView() },
|
||||
{ binding: 1, resource: { buffer: outputBuffer } }
|
||||
]
|
||||
})
|
||||
this.lastReadbackTexture = texture
|
||||
this.lastReadbackBuffer = outputBuffer
|
||||
}
|
||||
|
||||
const encoder = this.device.createCommandEncoder()
|
||||
const pass = encoder.beginComputePass()
|
||||
pass.setPipeline(this.readbackPipeline)
|
||||
pass.setBindGroup(0, this.readbackBindGroup)
|
||||
|
||||
const width = texture.width
|
||||
const height = texture.height
|
||||
// Dispatch workgroups based on texture dimensions (8x8 block size)
|
||||
pass.dispatchWorkgroups(Math.ceil(width / 8), Math.ceil(height / 8))
|
||||
pass.end()
|
||||
|
||||
this.device.queue.submit([encoder.finish()])
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
this.quadVertexBuffer.destroy()
|
||||
this.indexBuffer.destroy()
|
||||
this.instanceBuffer.destroy()
|
||||
this.uniformBuffer.destroy()
|
||||
if (this.currentStrokeTexture) this.currentStrokeTexture.destroy()
|
||||
|
||||
// Clear cached bind groups
|
||||
this.compositeTextureBindGroup = null
|
||||
this.previewTextureBindGroup = null
|
||||
this.readbackBindGroup = null
|
||||
this.backgroundBindGroup = null
|
||||
this.lastReadbackTexture = null
|
||||
this.lastReadbackBuffer = null
|
||||
this.lastBackgroundTexture = null
|
||||
}
|
||||
}
|
||||
171
src/composables/maskeditor/gpu/brushShaders.ts
Normal file
171
src/composables/maskeditor/gpu/brushShaders.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import tgpu from 'typegpu'
|
||||
import * as d from 'typegpu/data'
|
||||
import { BrushUniforms } from './gpuSchema'
|
||||
|
||||
const VertexOutput = d.struct({
|
||||
position: d.builtin.position,
|
||||
localUV: d.location(0, d.vec2f),
|
||||
color: d.location(1, d.vec3f),
|
||||
opacity: d.location(2, d.f32),
|
||||
hardness: d.location(3, d.f32)
|
||||
})
|
||||
|
||||
const brushVertexTemplate = `
|
||||
@group(0) @binding(0) var<uniform> globals: BrushUniforms;
|
||||
|
||||
@vertex
|
||||
fn vs(
|
||||
@location(0) quadPos: vec2<f32>,
|
||||
@location(1) pos: vec2<f32>,
|
||||
@location(2) size: f32,
|
||||
@location(3) pressure: f32
|
||||
) -> VertexOutput {
|
||||
// Convert diameter to radius
|
||||
let radius = size * pressure;
|
||||
let pixelPos = pos + (quadPos * radius);
|
||||
|
||||
// Convert pixel coordinates to Normalized Device Coordinates (NDC)
|
||||
let ndcX = (pixelPos.x / globals.screenSize.x) * 2.0 - 1.0;
|
||||
let ndcY = 1.0 - ((pixelPos.y / globals.screenSize.y) * 2.0); // Flip Y axis for WebGPU coordinate system
|
||||
|
||||
return VertexOutput(
|
||||
vec4<f32>(ndcX, ndcY, 0.0, 1.0),
|
||||
quadPos,
|
||||
globals.brushColor,
|
||||
pressure * globals.brushOpacity,
|
||||
globals.hardness
|
||||
);
|
||||
}
|
||||
`
|
||||
|
||||
export const brushVertex = tgpu.resolve({
|
||||
template: brushVertexTemplate,
|
||||
externals: {
|
||||
BrushUniforms,
|
||||
VertexOutput
|
||||
}
|
||||
})
|
||||
|
||||
const brushFragmentTemplate = `
|
||||
@group(0) @binding(0) var<uniform> globals: BrushUniforms;
|
||||
|
||||
@fragment
|
||||
fn fs(v: VertexOutput) -> @location(0) vec4<f32> {
|
||||
var dist: f32;
|
||||
if (globals.brushShape == 1u) {
|
||||
// Calculate Chebyshev distance for square shape
|
||||
dist = max(abs(v.localUV.x), abs(v.localUV.y));
|
||||
} else {
|
||||
// Calculate Euclidean distance for circle shape
|
||||
dist = length(v.localUV);
|
||||
}
|
||||
|
||||
if (dist > 1.0) { discard; }
|
||||
|
||||
// Calculate alpha with hardness and anti-aliasing
|
||||
let edgeWidth = fwidth(dist);
|
||||
let startFade = min(v.hardness, 1.0 - edgeWidth * 2.0);
|
||||
let linearAlpha = 1.0 - smoothstep(startFade, 1.0, dist);
|
||||
// Apply quadratic falloff for smoother edges
|
||||
let alphaShape = pow(linearAlpha, 2.0);
|
||||
|
||||
// Return premultiplied alpha color
|
||||
let alpha = alphaShape * v.opacity;
|
||||
return vec4<f32>(v.color * alpha, alpha);
|
||||
}
|
||||
`
|
||||
|
||||
export const brushFragment = tgpu.resolve({
|
||||
template: brushFragmentTemplate,
|
||||
externals: {
|
||||
VertexOutput,
|
||||
BrushUniforms
|
||||
}
|
||||
})
|
||||
|
||||
const blitShaderTemplate = `
|
||||
@vertex fn vs(@builtin(vertex_index) vIdx: u32) -> @builtin(position) vec4<f32> {
|
||||
var pos = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0)
|
||||
);
|
||||
return vec4<f32>(pos[vIdx], 0.0, 1.0);
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var myTexture: texture_2d<f32>;
|
||||
|
||||
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let c = textureLoad(myTexture, vec2<i32>(pos.xy), 0);
|
||||
// Treat texture as premultiplied to prevent double-darkening on overlaps
|
||||
return c;
|
||||
}
|
||||
`
|
||||
|
||||
export const blitShader = tgpu.resolve({
|
||||
template: blitShaderTemplate,
|
||||
externals: {}
|
||||
})
|
||||
|
||||
const compositeShaderTemplate = `
|
||||
@vertex fn vs(@builtin(vertex_index) vIdx: u32) -> @builtin(position) vec4<f32> {
|
||||
var pos = array<vec2<f32>, 3>(
|
||||
vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0)
|
||||
);
|
||||
return vec4<f32>(pos[vIdx], 0.0, 1.0);
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var myTexture: texture_2d<f32>;
|
||||
@group(1) @binding(0) var<uniform> globals: BrushUniforms;
|
||||
|
||||
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let sampled = textureLoad(myTexture, vec2<i32>(pos.xy), 0);
|
||||
// Apply global brush opacity to accumulated coverage
|
||||
return sampled * globals.brushOpacity;
|
||||
}
|
||||
`
|
||||
|
||||
export const compositeShader = tgpu.resolve({
|
||||
template: compositeShaderTemplate,
|
||||
externals: {
|
||||
BrushUniforms
|
||||
}
|
||||
})
|
||||
|
||||
const readbackShaderTemplate = `
|
||||
@group(0) @binding(0) var inputTex: texture_2d<f32>;
|
||||
@group(0) @binding(1) var<storage, read_write> outputBuf: array<u32>;
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let dims = textureDimensions(inputTex);
|
||||
if (id.x >= dims.x || id.y >= dims.y) { return; }
|
||||
|
||||
let color = textureLoad(inputTex, vec2<i32>(id.xy), 0);
|
||||
|
||||
var r = color.r;
|
||||
var g = color.g;
|
||||
var b = color.b;
|
||||
let a = color.a;
|
||||
|
||||
if (a > 0.0) {
|
||||
r = r / a;
|
||||
g = g / a;
|
||||
b = b / a;
|
||||
}
|
||||
|
||||
let ir = u32(clamp(r * 255.0, 0.0, 255.0));
|
||||
let ig = u32(clamp(g * 255.0, 0.0, 255.0));
|
||||
let ib = u32(clamp(b * 255.0, 0.0, 255.0));
|
||||
let ia = u32(clamp(a * 255.0, 0.0, 255.0));
|
||||
|
||||
// Pack RGBA channels into a single u32 (Little Endian)
|
||||
let packed = ir | (ig << 8u) | (ib << 16u) | (ia << 24u);
|
||||
|
||||
let index = id.y * dims.x + id.x;
|
||||
outputBuf[index] = packed;
|
||||
}
|
||||
`
|
||||
|
||||
export const readbackShader = tgpu.resolve({
|
||||
template: readbackShaderTemplate,
|
||||
externals: {}
|
||||
})
|
||||
17
src/composables/maskeditor/gpu/gpuSchema.ts
Normal file
17
src/composables/maskeditor/gpu/gpuSchema.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import * as d from 'typegpu/data'
|
||||
|
||||
// Global brush uniforms
|
||||
export const BrushUniforms = d.struct({
|
||||
brushColor: d.vec3f,
|
||||
brushOpacity: d.f32,
|
||||
hardness: d.f32,
|
||||
screenSize: d.vec2f,
|
||||
brushShape: d.u32 // 0: Circle, 1: Square
|
||||
})
|
||||
|
||||
// Per-point instance data
|
||||
export const StrokePoint = d.struct({
|
||||
pos: d.location(0, d.vec2f), // Center position
|
||||
size: d.location(1, d.f32), // Brush radius
|
||||
pressure: d.location(2, d.f32) // Pressure value (0.0 - 1.0)
|
||||
})
|
||||
126
src/composables/maskeditor/splineUtils.ts
Normal file
126
src/composables/maskeditor/splineUtils.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import type { Point } from '@/extensions/core/maskeditor/types'
|
||||
|
||||
/**
|
||||
* Evaluates a Catmull-Rom spline at parameter t between p1 and p2
|
||||
* @param p0 Previous control point
|
||||
* @param p1 Start point of the curve segment
|
||||
* @param p2 End point of the curve segment
|
||||
* @param p3 Next control point
|
||||
* @param t Parameter in range [0, 1]
|
||||
* @returns Interpolated point on the curve
|
||||
*/
|
||||
export function catmullRomSpline(
|
||||
p0: Point,
|
||||
p1: Point,
|
||||
p2: Point,
|
||||
p3: Point,
|
||||
t: number
|
||||
): Point {
|
||||
// Centripetal Catmull-Rom Spline (alpha = 0.5) to prevent loops and overshoots
|
||||
const alpha = 0.5
|
||||
|
||||
const getT = (t: number, p0: Point, p1: Point) => {
|
||||
const d = Math.hypot(p1.x - p0.x, p1.y - p0.y)
|
||||
return t + Math.pow(d, alpha)
|
||||
}
|
||||
|
||||
const t0 = 0
|
||||
const t1 = getT(t0, p0, p1)
|
||||
const t2 = getT(t1, p1, p2)
|
||||
const t3 = getT(t2, p2, p3)
|
||||
|
||||
// Map normalized t to parameter range
|
||||
const tInterp = t1 + (t2 - t1) * t
|
||||
|
||||
// Safe interpolation for coincident points
|
||||
const interp = (
|
||||
pA: Point,
|
||||
pB: Point,
|
||||
tA: number,
|
||||
tB: number,
|
||||
t: number
|
||||
): Point => {
|
||||
if (Math.abs(tB - tA) < 0.0001) return pA
|
||||
const k = (t - tA) / (tB - tA)
|
||||
return add(mul(pA, 1 - k), mul(pB, k))
|
||||
}
|
||||
|
||||
// Barry-Goldman pyramidal interpolation
|
||||
const A1 = interp(p0, p1, t0, t1, tInterp)
|
||||
const A2 = interp(p1, p2, t1, t2, tInterp)
|
||||
const A3 = interp(p2, p3, t2, t3, tInterp)
|
||||
|
||||
const B1 = interp(A1, A2, t0, t2, tInterp)
|
||||
const B2 = interp(A2, A3, t1, t3, tInterp)
|
||||
|
||||
const C = interp(B1, B2, t1, t2, tInterp)
|
||||
|
||||
return C
|
||||
}
|
||||
|
||||
function add(p1: Point, p2: Point): Point {
|
||||
return { x: p1.x + p2.x, y: p1.y + p2.y }
|
||||
}
|
||||
|
||||
function mul(p: Point, s: number): Point {
|
||||
return { x: p.x * s, y: p.y * s }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resamples a curve segment with a starting offset (remainder from previous segment).
|
||||
* Returns the resampled points and the new remainder distance.
|
||||
*
|
||||
* @param points Points defining the curve segment
|
||||
* @param spacing Desired spacing between points
|
||||
* @param startOffset Distance to travel before placing the first point (remainder)
|
||||
* @returns Object containing points and new remainder
|
||||
*/
|
||||
export function resampleSegment(
|
||||
points: Point[],
|
||||
spacing: number,
|
||||
startOffset: number
|
||||
): { points: Point[]; remainder: number } {
|
||||
if (points.length === 0) return { points: [], remainder: startOffset }
|
||||
|
||||
const result: Point[] = []
|
||||
let currentDist = 0
|
||||
let nextSampleDist = startOffset
|
||||
|
||||
// Iterate through segment points
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p1 = points[i]
|
||||
const p2 = points[i + 1]
|
||||
|
||||
const dx = p2.x - p1.x
|
||||
const dy = p2.y - p1.y
|
||||
const segmentLen = Math.hypot(dx, dy)
|
||||
|
||||
// Handle zero-length segments
|
||||
if (segmentLen < 0.0001) {
|
||||
while (nextSampleDist <= currentDist) {
|
||||
result.push(p1)
|
||||
nextSampleDist += spacing
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Generate samples within the segment
|
||||
while (nextSampleDist <= currentDist + segmentLen) {
|
||||
const t = (nextSampleDist - currentDist) / segmentLen
|
||||
|
||||
// Interpolate
|
||||
const x = p1.x + t * dx
|
||||
const y = p1.y + t * dy
|
||||
result.push({ x, y })
|
||||
|
||||
nextSampleDist += spacing
|
||||
}
|
||||
|
||||
currentDist += segmentLen
|
||||
}
|
||||
|
||||
// Calculate remainder distance for the next segment
|
||||
const remainder = nextSampleDist - currentDist
|
||||
|
||||
return { points: result, remainder }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,9 @@ import { useMaskEditorStore } from '@/stores/maskEditorStore'
|
||||
export function useCanvasHistory(maxStates = 20) {
|
||||
const store = useMaskEditorStore()
|
||||
|
||||
const states = ref<{ mask: ImageData; rgb: ImageData }[]>([])
|
||||
const states = ref<
|
||||
{ mask: ImageData | ImageBitmap; rgb: ImageData | ImageBitmap }[]
|
||||
>([])
|
||||
const currentStateIndex = ref(-1)
|
||||
const initialized = ref(false)
|
||||
|
||||
@@ -53,7 +55,10 @@ export function useCanvasHistory(maxStates = 20) {
|
||||
initialized.value = true
|
||||
}
|
||||
|
||||
const saveState = () => {
|
||||
const saveState = (
|
||||
providedMaskData?: ImageData | ImageBitmap,
|
||||
providedRgbData?: ImageData | ImageBitmap
|
||||
) => {
|
||||
const maskCtx = store.maskCtx
|
||||
const rgbCtx = store.rgbCtx
|
||||
const maskCanvas = store.maskCanvas
|
||||
@@ -68,23 +73,32 @@ export function useCanvasHistory(maxStates = 20) {
|
||||
|
||||
states.value = states.value.slice(0, currentStateIndex.value + 1)
|
||||
|
||||
const maskState = maskCtx.getImageData(
|
||||
0,
|
||||
0,
|
||||
maskCanvas.width,
|
||||
maskCanvas.height
|
||||
)
|
||||
const rgbState = rgbCtx.getImageData(
|
||||
0,
|
||||
0,
|
||||
rgbCanvas.width,
|
||||
rgbCanvas.height
|
||||
)
|
||||
let maskState: ImageData | ImageBitmap
|
||||
let rgbState: ImageData | ImageBitmap
|
||||
|
||||
if (providedMaskData && providedRgbData) {
|
||||
maskState = providedMaskData
|
||||
rgbState = providedRgbData
|
||||
} else {
|
||||
maskState = maskCtx.getImageData(
|
||||
0,
|
||||
0,
|
||||
maskCanvas.width,
|
||||
maskCanvas.height
|
||||
)
|
||||
rgbState = rgbCtx.getImageData(0, 0, rgbCanvas.width, rgbCanvas.height)
|
||||
}
|
||||
|
||||
states.value.push({ mask: maskState, rgb: rgbState })
|
||||
currentStateIndex.value++
|
||||
|
||||
if (states.value.length > maxStates) {
|
||||
states.value.shift()
|
||||
const removed = states.value.shift()
|
||||
// Cleanup ImageBitmaps to avoid memory leaks
|
||||
if (removed) {
|
||||
if (removed.mask instanceof ImageBitmap) removed.mask.close()
|
||||
if (removed.rgb instanceof ImageBitmap) removed.rgb.close()
|
||||
}
|
||||
currentStateIndex.value--
|
||||
}
|
||||
}
|
||||
@@ -109,16 +123,35 @@ export function useCanvasHistory(maxStates = 20) {
|
||||
restoreState(states.value[currentStateIndex.value])
|
||||
}
|
||||
|
||||
const restoreState = (state: { mask: ImageData; rgb: ImageData }) => {
|
||||
const restoreState = (state: {
|
||||
mask: ImageData | ImageBitmap
|
||||
rgb: ImageData | ImageBitmap
|
||||
}) => {
|
||||
const maskCtx = store.maskCtx
|
||||
const rgbCtx = store.rgbCtx
|
||||
if (!maskCtx || !rgbCtx) return
|
||||
|
||||
maskCtx.putImageData(state.mask, 0, 0)
|
||||
rgbCtx.putImageData(state.rgb, 0, 0)
|
||||
if (state.mask instanceof ImageBitmap) {
|
||||
maskCtx.clearRect(0, 0, state.mask.width, state.mask.height)
|
||||
maskCtx.drawImage(state.mask, 0, 0)
|
||||
} else {
|
||||
maskCtx.putImageData(state.mask, 0, 0)
|
||||
}
|
||||
|
||||
if (state.rgb instanceof ImageBitmap) {
|
||||
rgbCtx.clearRect(0, 0, state.rgb.width, state.rgb.height)
|
||||
rgbCtx.drawImage(state.rgb, 0, 0)
|
||||
} else {
|
||||
rgbCtx.putImageData(state.rgb, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
const clearStates = () => {
|
||||
// Cleanup bitmaps
|
||||
states.value.forEach((state) => {
|
||||
if (state.mask instanceof ImageBitmap) state.mask.close()
|
||||
if (state.rgb instanceof ImageBitmap) state.rgb.close()
|
||||
})
|
||||
states.value = []
|
||||
currentStateIndex.value = -1
|
||||
initialized.value = false
|
||||
@@ -127,6 +160,7 @@ export function useCanvasHistory(maxStates = 20) {
|
||||
return {
|
||||
canUndo,
|
||||
canRedo,
|
||||
currentStateIndex,
|
||||
saveInitialState,
|
||||
saveState,
|
||||
undo,
|
||||
|
||||
48
src/composables/maskeditor/useMaskEditor.ts
Normal file
48
src/composables/maskeditor/useMaskEditor.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
import TopBarHeader from '@/components/maskeditor/dialog/TopBarHeader.vue'
|
||||
import MaskEditorContent from '@/components/maskeditor/MaskEditorContent.vue'
|
||||
|
||||
export function useMaskEditor() {
|
||||
const openMaskEditor = (node: LGraphNode) => {
|
||||
if (!node) {
|
||||
console.error('[MaskEditor] No node provided')
|
||||
return
|
||||
}
|
||||
|
||||
if (!node.imgs?.length && node.previewMediaType !== 'image') {
|
||||
console.error('[MaskEditor] Node has no images')
|
||||
return
|
||||
}
|
||||
|
||||
useDialogStore().showDialog({
|
||||
key: 'global-mask-editor',
|
||||
headerComponent: TopBarHeader,
|
||||
component: MaskEditorContent,
|
||||
props: {
|
||||
node
|
||||
},
|
||||
dialogComponentProps: {
|
||||
style: 'width: 90vw; height: 90vh;',
|
||||
modal: true,
|
||||
maximizable: true,
|
||||
closable: true,
|
||||
pt: {
|
||||
root: {
|
||||
class: 'mask-editor-dialog flex flex-col'
|
||||
},
|
||||
content: {
|
||||
class: 'flex flex-col min-h-0 flex-1 !p-0'
|
||||
},
|
||||
header: {
|
||||
class: '!p-2'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
openMaskEditor
|
||||
}
|
||||
}
|
||||
@@ -80,21 +80,64 @@ export function useMaskEditorLoader() {
|
||||
try {
|
||||
validateNode(node)
|
||||
|
||||
const nodeImageUrl = getNodeImageUrl(node)
|
||||
let nodeImageUrl = getNodeImageUrl(node)
|
||||
|
||||
const nodeImageRef = parseImageRef(nodeImageUrl)
|
||||
let nodeImageRef = parseImageRef(nodeImageUrl)
|
||||
|
||||
let widgetFilename: string | undefined
|
||||
if (node.widgets) {
|
||||
const imageWidget = node.widgets.find((w) => w.name === 'image')
|
||||
if (
|
||||
imageWidget &&
|
||||
typeof imageWidget.value === 'object' &&
|
||||
imageWidget.value &&
|
||||
'filename' in imageWidget.value &&
|
||||
typeof imageWidget.value.filename === 'string'
|
||||
) {
|
||||
widgetFilename = imageWidget.value.filename
|
||||
if (imageWidget) {
|
||||
if (typeof imageWidget.value === 'string') {
|
||||
widgetFilename = imageWidget.value
|
||||
} else if (
|
||||
typeof imageWidget.value === 'object' &&
|
||||
imageWidget.value &&
|
||||
'filename' in imageWidget.value &&
|
||||
typeof imageWidget.value.filename === 'string'
|
||||
) {
|
||||
widgetFilename = imageWidget.value.filename
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a widget filename, we should prioritize it over the node image
|
||||
// because the node image might be stale (e.g. from a previous save)
|
||||
// while the widget value reflects the current selection.
|
||||
if (widgetFilename) {
|
||||
try {
|
||||
// Parse the widget value which might be in format "subfolder/filename [type]" or just "filename"
|
||||
let filename = widgetFilename
|
||||
let subfolder: string | undefined = undefined
|
||||
let type: string | undefined = 'input' // Default to input for widget values
|
||||
|
||||
// Check for type in brackets at the end
|
||||
const typeMatch = filename.match(/ \[([^\]]+)\]$/)
|
||||
if (typeMatch) {
|
||||
type = typeMatch[1]
|
||||
filename = filename.substring(
|
||||
0,
|
||||
filename.length - typeMatch[0].length
|
||||
)
|
||||
}
|
||||
|
||||
// Check for subfolder (forward slash separator)
|
||||
const lastSlashIndex = filename.lastIndexOf('/')
|
||||
if (lastSlashIndex !== -1) {
|
||||
subfolder = filename.substring(0, lastSlashIndex)
|
||||
filename = filename.substring(lastSlashIndex + 1)
|
||||
}
|
||||
|
||||
nodeImageRef = {
|
||||
filename,
|
||||
type,
|
||||
subfolder
|
||||
}
|
||||
|
||||
// We also need to update nodeImageUrl to match this new ref so subsequent logic works
|
||||
nodeImageUrl = mkFileUrl({ ref: nodeImageRef })
|
||||
} catch (e) {
|
||||
console.warn('Failed to parse widget filename as ref', e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1545,7 +1545,26 @@ const apiNodeCosts: Record<string, { displayPrice: string | PricingFunction }> =
|
||||
}
|
||||
},
|
||||
GeminiImageNode: {
|
||||
displayPrice: '$0.03 per 1K tokens'
|
||||
displayPrice: '~$0.039/Image (1K)'
|
||||
},
|
||||
GeminiImage2Node: {
|
||||
displayPrice: (node: LGraphNode): string => {
|
||||
const resolutionWidget = node.widgets?.find(
|
||||
(w) => w.name === 'resolution'
|
||||
) as IComboWidget
|
||||
|
||||
if (!resolutionWidget) return 'Token-based'
|
||||
|
||||
const resolution = String(resolutionWidget.value)
|
||||
if (resolution.includes('1K')) {
|
||||
return '~$0.134/Image'
|
||||
} else if (resolution.includes('2K')) {
|
||||
return '~$0.134/Image'
|
||||
} else if (resolution.includes('4K')) {
|
||||
return '~$0.24/Image'
|
||||
}
|
||||
return 'Token-based'
|
||||
}
|
||||
},
|
||||
// OpenAI nodes
|
||||
OpenAIChatNode: {
|
||||
@@ -1829,6 +1848,7 @@ export const useNodePricing = () => {
|
||||
TripoTextureNode: ['texture_quality'],
|
||||
// Google/Gemini nodes
|
||||
GeminiNode: ['model'],
|
||||
GeminiImage2Node: ['resolution'],
|
||||
// OpenAI nodes
|
||||
OpenAIChatNode: ['model'],
|
||||
// ByteDance
|
||||
|
||||
114
src/core/graph/widgets/dynamicWidgets.ts
Normal file
114
src/core/graph/widgets/dynamicWidgets.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
|
||||
import type { ComboInputSpec, InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import { zDynamicComboInputSpec } from '@/schemas/nodeDefSchema'
|
||||
import { useLitegraphService } from '@/services/litegraphService'
|
||||
import { app } from '@/scripts/app'
|
||||
import type { ComfyApp } from '@/scripts/app'
|
||||
|
||||
function dynamicComboWidget(
|
||||
node: LGraphNode,
|
||||
inputName: string,
|
||||
untypedInputData: InputSpec,
|
||||
appArg: ComfyApp,
|
||||
widgetName?: string
|
||||
) {
|
||||
const { addNodeInput } = useLitegraphService()
|
||||
const parseResult = zDynamicComboInputSpec.safeParse(untypedInputData)
|
||||
if (!parseResult.success) throw new Error('invalid DynamicCombo spec')
|
||||
const inputData = parseResult.data
|
||||
const options = Object.fromEntries(
|
||||
inputData[1].options.map(({ key, inputs }) => [key, inputs])
|
||||
)
|
||||
const subSpec: ComboInputSpec = [Object.keys(options), {}]
|
||||
const { widget, minWidth, minHeight } = app.widgets['COMBO'](
|
||||
node,
|
||||
inputName,
|
||||
subSpec,
|
||||
appArg,
|
||||
widgetName
|
||||
)
|
||||
let currentDynamicNames: string[] = []
|
||||
const updateWidgets = (value?: string) => {
|
||||
if (!node.widgets) throw new Error('Not Reachable')
|
||||
const newSpec = value ? options[value] : undefined
|
||||
//TODO: Calculate intersection for widgets that persist across options
|
||||
//This would potentially allow links to be retained
|
||||
for (const name of currentDynamicNames) {
|
||||
const inputIndex = node.inputs.findIndex((input) => input.name === name)
|
||||
if (inputIndex !== -1) node.removeInput(inputIndex)
|
||||
const widgetIndex = node.widgets.findIndex(
|
||||
(widget) => widget.name === name
|
||||
)
|
||||
if (widgetIndex === -1) continue
|
||||
node.widgets[widgetIndex].value = undefined
|
||||
node.widgets.splice(widgetIndex, 1)
|
||||
}
|
||||
currentDynamicNames = []
|
||||
if (!newSpec) return
|
||||
|
||||
const insertionPoint = node.widgets.findIndex((w) => w === widget) + 1
|
||||
const startingLength = node.widgets.length
|
||||
const inputInsertionPoint =
|
||||
node.inputs.findIndex((i) => i.name === widget.name) + 1
|
||||
const startingInputLength = node.inputs.length
|
||||
if (insertionPoint === 0)
|
||||
throw new Error("Dynamic widget doesn't exist on node")
|
||||
const inputTypes: [Record<string, InputSpec> | undefined, boolean][] = [
|
||||
[newSpec.required, false],
|
||||
[newSpec.optional, true]
|
||||
]
|
||||
for (const [inputType, isOptional] of inputTypes)
|
||||
for (const name in inputType ?? {}) {
|
||||
addNodeInput(
|
||||
node,
|
||||
transformInputSpecV1ToV2(inputType![name], {
|
||||
name,
|
||||
isOptional
|
||||
})
|
||||
)
|
||||
currentDynamicNames.push(name)
|
||||
}
|
||||
|
||||
const addedWidgets = node.widgets.splice(startingLength)
|
||||
node.widgets.splice(insertionPoint, 0, ...addedWidgets)
|
||||
if (inputInsertionPoint === 0) {
|
||||
if (
|
||||
addedWidgets.length === 0 &&
|
||||
node.inputs.length !== startingInputLength
|
||||
)
|
||||
//input is inputOnly, but lacks an insertion point
|
||||
throw new Error('Failed to find input socket for ' + widget.name)
|
||||
return
|
||||
}
|
||||
const addedInputs = node
|
||||
.spliceInputs(startingInputLength)
|
||||
.map((addedInput) => {
|
||||
const existingInput = node.inputs.findIndex(
|
||||
(existingInput) => addedInput.name === existingInput.name
|
||||
)
|
||||
return existingInput === -1
|
||||
? addedInput
|
||||
: node.spliceInputs(existingInput, 1)[0]
|
||||
})
|
||||
//assume existing inputs are in correct order
|
||||
node.spliceInputs(inputInsertionPoint, 0, ...addedInputs)
|
||||
node.size[1] = node.computeSize([...node.size])[1]
|
||||
}
|
||||
//A little hacky, but onConfigure won't work.
|
||||
//It fires too late and is overly disruptive
|
||||
let widgetValue = widget.value
|
||||
Object.defineProperty(widget, 'value', {
|
||||
get() {
|
||||
return widgetValue
|
||||
},
|
||||
set(value) {
|
||||
widgetValue = value
|
||||
updateWidgets(value)
|
||||
}
|
||||
})
|
||||
widget.value = widgetValue
|
||||
return { widget, minWidth, minHeight }
|
||||
}
|
||||
|
||||
export const dynamicWidgets = { COMFY_DYNAMICCOMBO_V3: dynamicComboWidget }
|
||||
@@ -5,10 +5,9 @@ import { app } from '@/scripts/app'
|
||||
import { ComfyApp } from '@/scripts/app'
|
||||
import { useMaskEditorStore } from '@/stores/maskEditorStore'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
import MaskEditorContent from '@/components/maskeditor/MaskEditorContent.vue'
|
||||
import TopBarHeader from '@/components/maskeditor/dialog/TopBarHeader.vue'
|
||||
import { MaskEditorDialogOld } from './maskEditorOld'
|
||||
import { ClipspaceDialog } from './clipspace'
|
||||
import { useMaskEditor } from '@/composables/maskeditor/useMaskEditor'
|
||||
|
||||
function openMaskEditor(node: LGraphNode): void {
|
||||
if (!node) {
|
||||
@@ -26,32 +25,7 @@ function openMaskEditor(node: LGraphNode): void {
|
||||
)
|
||||
|
||||
if (useNewEditor) {
|
||||
// Use new refactored editor
|
||||
useDialogStore().showDialog({
|
||||
key: 'global-mask-editor',
|
||||
headerComponent: TopBarHeader,
|
||||
component: MaskEditorContent,
|
||||
props: {
|
||||
node
|
||||
},
|
||||
dialogComponentProps: {
|
||||
style: 'width: 90vw; height: 90vh;',
|
||||
modal: true,
|
||||
maximizable: true,
|
||||
closable: true,
|
||||
pt: {
|
||||
root: {
|
||||
class: 'mask-editor-dialog flex flex-col'
|
||||
},
|
||||
content: {
|
||||
class: 'flex flex-col min-h-0 flex-1 !p-0'
|
||||
},
|
||||
header: {
|
||||
class: '!p-2'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
useMaskEditor().openMaskEditor(node)
|
||||
} else {
|
||||
// Use old editor
|
||||
ComfyApp.copyToClipspace(node)
|
||||
|
||||
@@ -61,5 +61,5 @@ export interface Brush {
|
||||
size: number
|
||||
opacity: number
|
||||
hardness: number
|
||||
smoothingPrecision: number
|
||||
stepSize: number
|
||||
}
|
||||
|
||||
@@ -17,10 +17,10 @@ useExtensionService().registerExtension({
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
onNodeCreated ? onNodeCreated.apply(this, []) : undefined
|
||||
|
||||
const showValueWidget = ComfyWidgets['STRING'](
|
||||
const showValueWidget = ComfyWidgets['MARKDOWN'](
|
||||
this,
|
||||
'preview',
|
||||
['STRING', { multiline: true }],
|
||||
['MARKDOWN', {}],
|
||||
app
|
||||
).widget as DOMWidget<HTMLTextAreaElement, string>
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ export type {
|
||||
LGraphTriggerParam
|
||||
} from './types/graphTriggers'
|
||||
|
||||
export type rendererType = 'LG' | 'Vue'
|
||||
export type RendererType = 'LG' | 'Vue'
|
||||
|
||||
export interface LGraphState {
|
||||
lastGroupId: number
|
||||
@@ -106,7 +106,7 @@ export interface LGraphExtra extends Dictionary<unknown> {
|
||||
reroutes?: SerialisableReroute[]
|
||||
linkExtensions?: { id: number; parentId: number | undefined }[]
|
||||
ds?: DragAndScaleState
|
||||
workflowRendererVersion?: rendererType
|
||||
workflowRendererVersion?: RendererType
|
||||
}
|
||||
|
||||
export interface BaseLGraph {
|
||||
|
||||
@@ -1771,18 +1771,19 @@ export class LGraphCanvas
|
||||
}
|
||||
|
||||
static onMenuNodeClone(
|
||||
// @ts-expect-error - unused parameter
|
||||
value: IContextMenuValue,
|
||||
// @ts-expect-error - unused parameter
|
||||
options: IContextMenuOptions,
|
||||
// @ts-expect-error - unused parameter
|
||||
e: MouseEvent,
|
||||
// @ts-expect-error - unused parameter
|
||||
menu: ContextMenu,
|
||||
_value: IContextMenuValue,
|
||||
_options: IContextMenuOptions,
|
||||
_e: MouseEvent,
|
||||
_menu: ContextMenu,
|
||||
node: LGraphNode
|
||||
): void {
|
||||
const canvas = LGraphCanvas.active_canvas
|
||||
const nodes = canvas.selectedItems.size ? canvas.selectedItems : [node]
|
||||
const nodes = canvas.selectedItems.size ? [...canvas.selectedItems] : [node]
|
||||
if (nodes.length) LGraphCanvas.cloneNodes(nodes)
|
||||
}
|
||||
|
||||
static cloneNodes(nodes: Positionable[]) {
|
||||
const canvas = LGraphCanvas.active_canvas
|
||||
|
||||
// Find top-left-most boundary
|
||||
let offsetX = Infinity
|
||||
@@ -1792,11 +1793,11 @@ export class LGraphCanvas
|
||||
throw new TypeError(
|
||||
'Invalid node encountered on clone. `pos` was null.'
|
||||
)
|
||||
if (item.pos[0] < offsetX) offsetX = item.pos[0]
|
||||
if (item.pos[1] < offsetY) offsetY = item.pos[1]
|
||||
offsetX = Math.min(offsetX, item.pos[0])
|
||||
offsetY = Math.min(offsetY, item.pos[1])
|
||||
}
|
||||
|
||||
canvas._deserializeItems(canvas._serializeItems(nodes), {
|
||||
return canvas._deserializeItems(canvas._serializeItems(nodes), {
|
||||
position: [offsetX + 5, offsetY + 5]
|
||||
})
|
||||
}
|
||||
|
||||
@@ -848,15 +848,13 @@ export class LGraphNode
|
||||
}
|
||||
|
||||
if (info.widgets_values) {
|
||||
const widgetsWithValue = this.widgets.filter(
|
||||
(w) => w.serialize !== false
|
||||
const widgetsWithValue = this.widgets
|
||||
.values()
|
||||
.filter((w) => w.serialize !== false)
|
||||
.filter((_w, idx) => idx < info.widgets_values!.length)
|
||||
widgetsWithValue.forEach(
|
||||
(widget, i) => (widget.value = info.widgets_values![i])
|
||||
)
|
||||
for (let i = 0; i < info.widgets_values.length; ++i) {
|
||||
const widget = widgetsWithValue[i]
|
||||
if (widget) {
|
||||
widget.value = info.widgets_values[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -884,7 +882,7 @@ export class LGraphNode
|
||||
|
||||
// special case for when there were errors
|
||||
if (this.constructor === LGraphNode && this.last_serialization)
|
||||
return this.last_serialization
|
||||
return { ...this.last_serialization, mode: o.mode, pos: o.pos }
|
||||
|
||||
if (this.inputs)
|
||||
o.inputs = this.inputs.map((input) => inputAsSerialisable(input))
|
||||
@@ -1652,6 +1650,19 @@ export class LGraphNode
|
||||
this.onInputRemoved?.(slot, slot_info[0])
|
||||
this.setDirtyCanvas(true, true)
|
||||
}
|
||||
spliceInputs(
|
||||
startIndex: number,
|
||||
deleteCount = -1,
|
||||
...toAdd: INodeInputSlot[]
|
||||
): INodeInputSlot[] {
|
||||
if (deleteCount < 0) return this.inputs.splice(startIndex)
|
||||
const ret = this.inputs.splice(startIndex, deleteCount, ...toAdd)
|
||||
this.inputs.slice(startIndex).forEach((input, index) => {
|
||||
const link = input.link && this.graph?.links?.get(input.link)
|
||||
if (link) link.target_slot = startIndex + index
|
||||
})
|
||||
return ret
|
||||
}
|
||||
|
||||
/**
|
||||
* computes the minimum size of a node according to its inputs and output slots
|
||||
|
||||
@@ -1186,7 +1186,8 @@
|
||||
"Vue Nodes": "Vue Nodes",
|
||||
"Canvas Navigation": "Canvas Navigation",
|
||||
"PlanCredits": "Plan & Credits",
|
||||
"VueNodes": "Vue Nodes"
|
||||
"VueNodes": "Vue Nodes",
|
||||
"Nodes 2_0": "Nodes 2.0"
|
||||
},
|
||||
"serverConfigItems": {
|
||||
"listen": {
|
||||
@@ -1436,6 +1437,7 @@
|
||||
"INT": "INT",
|
||||
"LATENT": "LATENT",
|
||||
"LATENT_OPERATION": "LATENT_OPERATION",
|
||||
"LATENT_UPSCALE_MODEL": "LATENT_UPSCALE_MODEL",
|
||||
"LOAD_3D": "LOAD_3D",
|
||||
"LOAD_3D_ANIMATION": "LOAD_3D_ANIMATION",
|
||||
"LOAD3D_CAMERA": "LOAD3D_CAMERA",
|
||||
@@ -2075,7 +2077,36 @@
|
||||
"failedToCreateNode": "Failed to create node. Please try again or check console for details.",
|
||||
"noModelsInFolder": "No {type} available in this folder",
|
||||
"searchAssetsPlaceholder": "Type to search...",
|
||||
"uploadModel": "Upload model",
|
||||
"uploadModel": "Import model",
|
||||
"uploadModelFromCivitai": "Import a model from Civitai",
|
||||
"uploadModelFailedToRetrieveMetadata": "Failed to retrieve metadata. Please check the link and try again.",
|
||||
"onlyCivitaiUrlsSupported": "Only Civitai URLs are supported",
|
||||
"uploadModelDescription1": "Paste a Civitai model download link to add it to your library.",
|
||||
"uploadModelDescription2": "Only links from https://civitai.com are supported at the moment",
|
||||
"uploadModelDescription3": "Max file size: 1 GB",
|
||||
"civitaiLinkLabel": "Civitai model download link",
|
||||
"civitaiLinkPlaceholder": "Paste link here",
|
||||
"civitaiLinkExample": "Example: https://civitai.com/api/download/models/833921?type=Model&format=SafeTensor",
|
||||
"confirmModelDetails": "Confirm Model Details",
|
||||
"fileName": "File Name",
|
||||
"fileSize": "File Size",
|
||||
"modelName": "Model Name",
|
||||
"modelNamePlaceholder": "Enter a name for this model",
|
||||
"tags": "Tags",
|
||||
"tagsPlaceholder": "e.g., models, checkpoint",
|
||||
"tagsHelp": "Separate tags with commas",
|
||||
"upload": "Import",
|
||||
"uploadingModel": "Importing model...",
|
||||
"uploadSuccess": "Model imported successfully!",
|
||||
"uploadFailed": "Import failed",
|
||||
"modelAssociatedWithLink": "The model associated with the link you provided:",
|
||||
"modelTypeSelectorLabel": "What type of model is this?",
|
||||
"modelTypeSelectorPlaceholder": "Select model type",
|
||||
"selectModelType": "Select model type",
|
||||
"notSureLeaveAsIs": "Not sure? Just leave this as is",
|
||||
"modelUploaded": "Model imported! 🎉",
|
||||
"findInLibrary": "Find it in the {type} section of the models library.",
|
||||
"finish": "Finish",
|
||||
"allModels": "All Models",
|
||||
"allCategory": "All {category}",
|
||||
"unknown": "Unknown",
|
||||
@@ -2087,6 +2118,13 @@
|
||||
"sortZA": "Z-A",
|
||||
"sortRecent": "Recent",
|
||||
"sortPopular": "Popular",
|
||||
"errorFileTooLarge": "File exceeds the maximum allowed size limit",
|
||||
"errorFormatNotAllowed": "Only SafeTensor format is allowed",
|
||||
"errorUnsafePickleScan": "CivitAI detected potentially unsafe code in this file",
|
||||
"errorUnsafeVirusScan": "CivitAI detected malware or suspicious content in this file",
|
||||
"errorModelTypeNotSupported": "This model type is not supported",
|
||||
"errorUnknown": "An unexpected error occurred",
|
||||
"errorUploadFailed": "Failed to import asset. Please try again.",
|
||||
"ariaLabel": {
|
||||
"assetCard": "{name} - {type} asset",
|
||||
"loadingAsset": "Loading asset"
|
||||
@@ -2161,6 +2199,10 @@
|
||||
"vueNodesMigrationMainMenu": {
|
||||
"message": "Switch back to Nodes 2.0 anytime from the main menu."
|
||||
},
|
||||
"linearMode": {
|
||||
"share": "Share",
|
||||
"openWorkflow": "Open Workflow"
|
||||
},
|
||||
"missingNodes": {
|
||||
"cloud": {
|
||||
"title": "These nodes aren't available on Comfy Cloud yet",
|
||||
|
||||
@@ -2001,7 +2001,29 @@
|
||||
}
|
||||
},
|
||||
"EmptyHunyuanLatentVideo": {
|
||||
"display_name": "EmptyHunyuanLatentVideo",
|
||||
"display_name": "Empty HunyuanVideo 1.0 Latent",
|
||||
"inputs": {
|
||||
"width": {
|
||||
"name": "width"
|
||||
},
|
||||
"height": {
|
||||
"name": "height"
|
||||
},
|
||||
"length": {
|
||||
"name": "length"
|
||||
},
|
||||
"batch_size": {
|
||||
"name": "batch_size"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"tooltip": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"EmptyHunyuanVideo15Latent": {
|
||||
"display_name": "Empty HunyuanVideo 1.5 Latent",
|
||||
"inputs": {
|
||||
"width": {
|
||||
"name": "width"
|
||||
@@ -2574,6 +2596,54 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"GeminiImage2Node": {
|
||||
"display_name": "Nano Banana Pro (Google Gemini Image)",
|
||||
"description": "Generate or edit images synchronously via Google Vertex API.",
|
||||
"inputs": {
|
||||
"prompt": {
|
||||
"name": "prompt",
|
||||
"tooltip": "Text prompt describing the image to generate or the edits to apply. Include any constraints, styles, or details the model should follow."
|
||||
},
|
||||
"model": {
|
||||
"name": "model"
|
||||
},
|
||||
"seed": {
|
||||
"name": "seed",
|
||||
"tooltip": "When the seed is fixed to a specific value, the model makes a best effort to provide the same response for repeated requests. Deterministic output isn't guaranteed. Also, changing the model or parameter settings, such as the temperature, can cause variations in the response even when you use the same seed value. By default, a random seed value is used."
|
||||
},
|
||||
"aspect_ratio": {
|
||||
"name": "aspect_ratio",
|
||||
"tooltip": "If set to 'auto', matches your input image's aspect ratio; if no image is provided, generates a 1:1 square."
|
||||
},
|
||||
"resolution": {
|
||||
"name": "resolution",
|
||||
"tooltip": "Target output resolution. For 2K/4K the native Gemini upscaler is used."
|
||||
},
|
||||
"response_modalities": {
|
||||
"name": "response_modalities",
|
||||
"tooltip": "Choose 'IMAGE' for image-only output, or 'IMAGE+TEXT' to return both the generated image and a text response."
|
||||
},
|
||||
"images": {
|
||||
"name": "images",
|
||||
"tooltip": "Optional reference image(s). To include multiple images, use the Batch Images node (up to 14)."
|
||||
},
|
||||
"files": {
|
||||
"name": "files",
|
||||
"tooltip": "Optional file(s) to use as context for the model. Accepts inputs from the Gemini Generate Content Input Files node."
|
||||
},
|
||||
"control_after_generate": {
|
||||
"name": "control after generate"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"tooltip": null
|
||||
},
|
||||
"1": {
|
||||
"tooltip": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"GeminiImageNode": {
|
||||
"display_name": "Nano Banana (Google Gemini Image)",
|
||||
"description": "Edit images synchronously via Google API.",
|
||||
@@ -2602,6 +2672,10 @@
|
||||
"name": "aspect_ratio",
|
||||
"tooltip": "Defaults to matching the output image size to that of your input image, or otherwise generates 1:1 squares."
|
||||
},
|
||||
"response_modalities": {
|
||||
"name": "response_modalities",
|
||||
"tooltip": "Choose 'IMAGE' for image-only output, or 'IMAGE+TEXT' to return both the generated image and a text response."
|
||||
},
|
||||
"control_after_generate": {
|
||||
"name": "control after generate"
|
||||
}
|
||||
@@ -2905,6 +2979,120 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"HunyuanVideo15ImageToVideo": {
|
||||
"display_name": "HunyuanVideo15ImageToVideo",
|
||||
"inputs": {
|
||||
"positive": {
|
||||
"name": "positive"
|
||||
},
|
||||
"negative": {
|
||||
"name": "negative"
|
||||
},
|
||||
"vae": {
|
||||
"name": "vae"
|
||||
},
|
||||
"width": {
|
||||
"name": "width"
|
||||
},
|
||||
"height": {
|
||||
"name": "height"
|
||||
},
|
||||
"length": {
|
||||
"name": "length"
|
||||
},
|
||||
"batch_size": {
|
||||
"name": "batch_size"
|
||||
},
|
||||
"start_image": {
|
||||
"name": "start_image"
|
||||
},
|
||||
"clip_vision_output": {
|
||||
"name": "clip_vision_output"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "positive",
|
||||
"tooltip": null
|
||||
},
|
||||
"1": {
|
||||
"name": "negative",
|
||||
"tooltip": null
|
||||
},
|
||||
"2": {
|
||||
"name": "latent",
|
||||
"tooltip": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"HunyuanVideo15LatentUpscaleWithModel": {
|
||||
"display_name": "Hunyuan Video 15 Latent Upscale With Model",
|
||||
"inputs": {
|
||||
"model": {
|
||||
"name": "model"
|
||||
},
|
||||
"samples": {
|
||||
"name": "samples"
|
||||
},
|
||||
"upscale_method": {
|
||||
"name": "upscale_method"
|
||||
},
|
||||
"width": {
|
||||
"name": "width"
|
||||
},
|
||||
"height": {
|
||||
"name": "height"
|
||||
},
|
||||
"crop": {
|
||||
"name": "crop"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"tooltip": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"HunyuanVideo15SuperResolution": {
|
||||
"display_name": "HunyuanVideo15SuperResolution",
|
||||
"inputs": {
|
||||
"positive": {
|
||||
"name": "positive"
|
||||
},
|
||||
"negative": {
|
||||
"name": "negative"
|
||||
},
|
||||
"latent": {
|
||||
"name": "latent"
|
||||
},
|
||||
"noise_augmentation": {
|
||||
"name": "noise_augmentation"
|
||||
},
|
||||
"vae": {
|
||||
"name": "vae"
|
||||
},
|
||||
"start_image": {
|
||||
"name": "start_image"
|
||||
},
|
||||
"clip_vision_output": {
|
||||
"name": "clip_vision_output"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"name": "positive",
|
||||
"tooltip": null
|
||||
},
|
||||
"1": {
|
||||
"name": "negative",
|
||||
"tooltip": null
|
||||
},
|
||||
"2": {
|
||||
"name": "latent",
|
||||
"tooltip": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"HypernetworkLoader": {
|
||||
"display_name": "HypernetworkLoader",
|
||||
"inputs": {
|
||||
@@ -4566,6 +4754,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"LatentUpscaleModelLoader": {
|
||||
"display_name": "Load Latent Upscale Model",
|
||||
"inputs": {
|
||||
"model_name": {
|
||||
"name": "model_name"
|
||||
}
|
||||
},
|
||||
"outputs": {
|
||||
"0": {
|
||||
"tooltip": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"LazyCache": {
|
||||
"display_name": "LazyCache",
|
||||
"description": "A homebrew version of EasyCache - even 'easier' version of EasyCache to implement. Overall works worse than EasyCache, but better in some rare cases AND universal compatibility with everything in ComfyUI.",
|
||||
|
||||
@@ -335,11 +335,11 @@
|
||||
"name": "Validate workflows"
|
||||
},
|
||||
"Comfy_VueNodes_AutoScaleLayout": {
|
||||
"name": "Auto-scale layout (Vue nodes)",
|
||||
"name": "Auto-scale layout (Nodes 2.0)",
|
||||
"tooltip": "Automatically scale node positions when switching to Vue rendering to prevent overlap"
|
||||
},
|
||||
"Comfy_VueNodes_Enabled": {
|
||||
"name": "Modern Node Design (Vue Nodes)",
|
||||
"name": "Modern Node Design (Nodes 2.0)",
|
||||
"tooltip": "Modern: DOM-based rendering with enhanced interactivity, native browser features, and updated visual design. Classic: Traditional canvas rendering."
|
||||
},
|
||||
"Comfy_WidgetControlMode": {
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
:on-click="handleUploadClick"
|
||||
>
|
||||
<template #icon>
|
||||
<i class="icon-[lucide--upload]" />
|
||||
<i class="icon-[lucide--package-plus]" />
|
||||
</template>
|
||||
</IconTextButton>
|
||||
</div>
|
||||
@@ -73,11 +73,14 @@ import LeftSidePanel from '@/components/widget/panel/LeftSidePanel.vue'
|
||||
import { useFeatureFlags } from '@/composables/useFeatureFlags'
|
||||
import AssetFilterBar from '@/platform/assets/components/AssetFilterBar.vue'
|
||||
import AssetGrid from '@/platform/assets/components/AssetGrid.vue'
|
||||
import UploadModelDialog from '@/platform/assets/components/UploadModelDialog.vue'
|
||||
import UploadModelDialogHeader from '@/platform/assets/components/UploadModelDialogHeader.vue'
|
||||
import type { AssetDisplayItem } from '@/platform/assets/composables/useAssetBrowser'
|
||||
import { useAssetBrowser } from '@/platform/assets/composables/useAssetBrowser'
|
||||
import type { AssetItem } from '@/platform/assets/schemas/assetSchema'
|
||||
import { assetService } from '@/platform/assets/services/assetService'
|
||||
import { formatCategoryLabel } from '@/platform/assets/utils/categoryLabel'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
import { useModelToNodeStore } from '@/stores/modelToNodeStore'
|
||||
import { OnCloseKey } from '@/types/widgetTypes'
|
||||
|
||||
@@ -92,6 +95,7 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const dialogStore = useDialogStore()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'asset-select': [asset: AssetDisplayItem]
|
||||
@@ -189,6 +193,15 @@ const { flags } = useFeatureFlags()
|
||||
const isUploadButtonEnabled = computed(() => flags.modelUploadButtonEnabled)
|
||||
|
||||
function handleUploadClick() {
|
||||
// Will be implemented in the future commit
|
||||
dialogStore.showDialog({
|
||||
key: 'upload-model',
|
||||
headerComponent: UploadModelDialogHeader,
|
||||
component: UploadModelDialog,
|
||||
props: {
|
||||
onUploadSuccess: async () => {
|
||||
await execute()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -71,9 +71,10 @@
|
||||
</div>
|
||||
<div v-tooltip.top="$t('mediaAsset.actions.more')">
|
||||
<MoreButton
|
||||
ref="moreButtonRef"
|
||||
size="sm"
|
||||
@menu-opened="isMenuOpen = true"
|
||||
@menu-closed="isMenuOpen = false"
|
||||
@menu-opened="handleMenuOpened"
|
||||
@menu-closed="handleMenuClosed"
|
||||
@mouseenter="handleOverlayMouseEnter"
|
||||
@mouseleave="handleOverlayMouseLeave"
|
||||
>
|
||||
@@ -139,7 +140,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useElementHover } from '@vueuse/core'
|
||||
import { useElementHover, whenever } from '@vueuse/core'
|
||||
import { computed, defineAsyncComponent, provide, ref, toRef } from 'vue'
|
||||
|
||||
import IconButton from '@/components/button/IconButton.vue'
|
||||
@@ -189,7 +190,8 @@ const {
|
||||
selected,
|
||||
showOutputCount,
|
||||
outputCount,
|
||||
showDeleteButton
|
||||
showDeleteButton,
|
||||
openPopoverId
|
||||
} = defineProps<{
|
||||
asset?: AssetItem
|
||||
loading?: boolean
|
||||
@@ -197,15 +199,19 @@ const {
|
||||
showOutputCount?: boolean
|
||||
outputCount?: number
|
||||
showDeleteButton?: boolean
|
||||
openPopoverId?: string | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
zoom: [asset: AssetItem]
|
||||
'output-count-click': []
|
||||
'asset-deleted': []
|
||||
'popover-opened': []
|
||||
'popover-closed': []
|
||||
}>()
|
||||
|
||||
const cardContainerRef = ref<HTMLElement>()
|
||||
const moreButtonRef = ref<InstanceType<typeof MoreButton>>()
|
||||
|
||||
const isVideoPlaying = ref(false)
|
||||
const isMenuOpen = ref(false)
|
||||
@@ -339,4 +345,22 @@ const handleOutputCountClick = () => {
|
||||
const handleAssetDelete = () => {
|
||||
emit('asset-deleted')
|
||||
}
|
||||
|
||||
const handleMenuOpened = () => {
|
||||
isMenuOpen.value = true
|
||||
emit('popover-opened')
|
||||
}
|
||||
|
||||
const handleMenuClosed = () => {
|
||||
isMenuOpen.value = false
|
||||
emit('popover-closed')
|
||||
}
|
||||
|
||||
// Close this popover when another opens
|
||||
whenever(
|
||||
() => openPopoverId && openPopoverId !== asset?.id && isMenuOpen.value,
|
||||
() => {
|
||||
moreButtonRef.value?.hide()
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
58
src/platform/assets/components/UploadModelConfirmation.vue
Normal file
58
src/platform/assets/components/UploadModelConfirmation.vue
Normal file
@@ -0,0 +1,58 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- Model Info Section -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<p class="text-sm text-muted m-0">
|
||||
{{ $t('assetBrowser.modelAssociatedWithLink') }}
|
||||
</p>
|
||||
<p class="text-sm mt-0">
|
||||
{{ metadata?.name || metadata?.filename }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Model Type Selection -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-muted">
|
||||
{{ $t('assetBrowser.modelTypeSelectorLabel') }}
|
||||
</label>
|
||||
<SingleSelect
|
||||
v-model="selectedModelType"
|
||||
:label="
|
||||
isLoading
|
||||
? $t('g.loading')
|
||||
: $t('assetBrowser.modelTypeSelectorPlaceholder')
|
||||
"
|
||||
:options="modelTypes"
|
||||
:disabled="isLoading"
|
||||
/>
|
||||
<div class="flex items-center gap-2 text-sm text-muted">
|
||||
<i class="icon-[lucide--info]" />
|
||||
<span>{{ $t('assetBrowser.notSureLeaveAsIs') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import SingleSelect from '@/components/input/SingleSelect.vue'
|
||||
import { useModelTypes } from '@/platform/assets/composables/useModelTypes'
|
||||
import type { AssetMetadata } from '@/platform/assets/schemas/assetSchema'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: string | undefined
|
||||
metadata: AssetMetadata | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string | undefined]
|
||||
}>()
|
||||
|
||||
const { modelTypes, isLoading } = useModelTypes()
|
||||
|
||||
const selectedModelType = computed({
|
||||
get: () => props.modelValue ?? null,
|
||||
set: (value: string | null) => emit('update:modelValue', value ?? undefined)
|
||||
})
|
||||
</script>
|
||||
108
src/platform/assets/components/UploadModelDialog.vue
Normal file
108
src/platform/assets/components/UploadModelDialog.vue
Normal file
@@ -0,0 +1,108 @@
|
||||
<template>
|
||||
<div class="upload-model-dialog flex flex-col justify-between gap-6 p-4 pt-6">
|
||||
<!-- Step 1: Enter URL -->
|
||||
<UploadModelUrlInput
|
||||
v-if="currentStep === 1"
|
||||
v-model="wizardData.url"
|
||||
:error="uploadError"
|
||||
/>
|
||||
|
||||
<!-- Step 2: Confirm Metadata -->
|
||||
<UploadModelConfirmation
|
||||
v-else-if="currentStep === 2"
|
||||
v-model="selectedModelType"
|
||||
:metadata="wizardData.metadata"
|
||||
/>
|
||||
|
||||
<!-- Step 3: Upload Progress -->
|
||||
<UploadModelProgress
|
||||
v-else-if="currentStep === 3"
|
||||
:status="uploadStatus"
|
||||
:error="uploadError"
|
||||
:metadata="wizardData.metadata"
|
||||
:model-type="selectedModelType"
|
||||
/>
|
||||
|
||||
<!-- Navigation Footer -->
|
||||
<UploadModelFooter
|
||||
:current-step="currentStep"
|
||||
:is-fetching-metadata="isFetchingMetadata"
|
||||
:is-uploading="isUploading"
|
||||
:can-fetch-metadata="canFetchMetadata"
|
||||
:can-upload-model="canUploadModel"
|
||||
:upload-status="uploadStatus"
|
||||
@back="goToPreviousStep"
|
||||
@fetch-metadata="handleFetchMetadata"
|
||||
@upload="handleUploadModel"
|
||||
@close="handleClose"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
|
||||
import UploadModelConfirmation from '@/platform/assets/components/UploadModelConfirmation.vue'
|
||||
import UploadModelFooter from '@/platform/assets/components/UploadModelFooter.vue'
|
||||
import UploadModelProgress from '@/platform/assets/components/UploadModelProgress.vue'
|
||||
import UploadModelUrlInput from '@/platform/assets/components/UploadModelUrlInput.vue'
|
||||
import { useModelTypes } from '@/platform/assets/composables/useModelTypes'
|
||||
import { useUploadModelWizard } from '@/platform/assets/composables/useUploadModelWizard'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
|
||||
const dialogStore = useDialogStore()
|
||||
const { modelTypes, fetchModelTypes } = useModelTypes()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'upload-success': []
|
||||
}>()
|
||||
|
||||
const {
|
||||
currentStep,
|
||||
isFetchingMetadata,
|
||||
isUploading,
|
||||
uploadStatus,
|
||||
uploadError,
|
||||
wizardData,
|
||||
selectedModelType,
|
||||
canFetchMetadata,
|
||||
canUploadModel,
|
||||
fetchMetadata,
|
||||
uploadModel,
|
||||
goToPreviousStep
|
||||
} = useUploadModelWizard(modelTypes)
|
||||
|
||||
async function handleFetchMetadata() {
|
||||
await fetchMetadata()
|
||||
}
|
||||
|
||||
async function handleUploadModel() {
|
||||
const success = await uploadModel()
|
||||
if (success) {
|
||||
emit('upload-success')
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
dialogStore.closeDialog({ key: 'upload-model' })
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchModelTypes()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.upload-model-dialog {
|
||||
width: 90vw;
|
||||
max-width: 800px;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.upload-model-dialog {
|
||||
width: auto;
|
||||
min-width: 600px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
12
src/platform/assets/components/UploadModelDialogHeader.vue
Normal file
12
src/platform/assets/components/UploadModelDialogHeader.vue
Normal file
@@ -0,0 +1,12 @@
|
||||
<template>
|
||||
<div class="flex items-center gap-3 px-4 py-2 font-bold">
|
||||
<span>{{ $t('assetBrowser.uploadModelFromCivitai') }}</span>
|
||||
<span
|
||||
class="rounded-full bg-white px-1.5 py-0 text-xxs font-medium uppercase text-black"
|
||||
>
|
||||
{{ $t('g.beta') }}
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts"></script>
|
||||
72
src/platform/assets/components/UploadModelFooter.vue
Normal file
72
src/platform/assets/components/UploadModelFooter.vue
Normal file
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<div class="flex justify-end gap-2">
|
||||
<TextButton
|
||||
v-if="currentStep !== 1 && currentStep !== 3"
|
||||
:label="$t('g.back')"
|
||||
type="secondary"
|
||||
size="md"
|
||||
:disabled="isFetchingMetadata || isUploading"
|
||||
@click="emit('back')"
|
||||
/>
|
||||
<span v-else />
|
||||
|
||||
<IconTextButton
|
||||
v-if="currentStep === 1"
|
||||
:label="$t('g.continue')"
|
||||
type="primary"
|
||||
size="md"
|
||||
:disabled="!canFetchMetadata || isFetchingMetadata"
|
||||
@click="emit('fetchMetadata')"
|
||||
>
|
||||
<template #icon>
|
||||
<i
|
||||
v-if="isFetchingMetadata"
|
||||
class="icon-[lucide--loader-circle] animate-spin"
|
||||
/>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
<IconTextButton
|
||||
v-else-if="currentStep === 2"
|
||||
:label="$t('assetBrowser.upload')"
|
||||
type="primary"
|
||||
size="md"
|
||||
:disabled="!canUploadModel || isUploading"
|
||||
@click="emit('upload')"
|
||||
>
|
||||
<template #icon>
|
||||
<i
|
||||
v-if="isUploading"
|
||||
class="icon-[lucide--loader-circle] animate-spin"
|
||||
/>
|
||||
</template>
|
||||
</IconTextButton>
|
||||
<TextButton
|
||||
v-else-if="currentStep === 3 && uploadStatus === 'success'"
|
||||
:label="$t('assetBrowser.finish')"
|
||||
type="primary"
|
||||
size="md"
|
||||
@click="emit('close')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import IconTextButton from '@/components/button/IconTextButton.vue'
|
||||
import TextButton from '@/components/button/TextButton.vue'
|
||||
|
||||
defineProps<{
|
||||
currentStep: number
|
||||
isFetchingMetadata: boolean
|
||||
isUploading: boolean
|
||||
canFetchMetadata: boolean
|
||||
canUploadModel: boolean
|
||||
uploadStatus: 'idle' | 'uploading' | 'success' | 'error'
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'back'): void
|
||||
(e: 'fetchMetadata'): void
|
||||
(e: 'upload'): void
|
||||
(e: 'close'): void
|
||||
}>()
|
||||
</script>
|
||||
68
src/platform/assets/components/UploadModelProgress.vue
Normal file
68
src/platform/assets/components/UploadModelProgress.vue
Normal file
@@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<div class="flex flex-1 flex-col gap-6">
|
||||
<!-- Uploading State -->
|
||||
<div
|
||||
v-if="status === 'uploading'"
|
||||
class="flex flex-1 flex-col items-center justify-center gap-6"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--loader-circle] animate-spin text-6xl text-primary"
|
||||
/>
|
||||
<div class="text-center">
|
||||
<p class="m-0 text-sm font-bold">
|
||||
{{ $t('assetBrowser.uploadingModel') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Success State -->
|
||||
<div v-else-if="status === 'success'" class="flex flex-col gap-8">
|
||||
<div class="flex flex-col gap-4">
|
||||
<p class="text-sm text-muted m-0 font-bold">
|
||||
{{ $t('assetBrowser.modelUploaded') }}
|
||||
</p>
|
||||
<p class="text-sm text-muted m-0">
|
||||
{{ $t('assetBrowser.findInLibrary', { type: modelType }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row items-start p-8 bg-neutral-800 rounded-lg">
|
||||
<div class="flex flex-col justify-center items-start gap-1 flex-1">
|
||||
<p class="text-sm m-0">
|
||||
{{ metadata?.name || metadata?.filename }}
|
||||
</p>
|
||||
<p class="text-sm text-muted m-0">
|
||||
{{ modelType }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error State -->
|
||||
<div
|
||||
v-else-if="status === 'error'"
|
||||
class="flex flex-1 flex-col items-center justify-center gap-6"
|
||||
>
|
||||
<i class="icon-[lucide--x-circle] text-6xl text-error" />
|
||||
<div class="text-center">
|
||||
<p class="m-0 text-sm font-bold">
|
||||
{{ $t('assetBrowser.uploadFailed') }}
|
||||
</p>
|
||||
<p v-if="error" class="text-sm text-muted mb-0">
|
||||
{{ error }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { AssetMetadata } from '@/platform/assets/schemas/assetSchema'
|
||||
|
||||
defineProps<{
|
||||
status: 'idle' | 'uploading' | 'success' | 'error'
|
||||
error?: string
|
||||
metadata: AssetMetadata | null
|
||||
modelType: string | undefined
|
||||
}>()
|
||||
</script>
|
||||
49
src/platform/assets/components/UploadModelUrlInput.vue
Normal file
49
src/platform/assets/components/UploadModelUrlInput.vue
Normal file
@@ -0,0 +1,49 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-2">
|
||||
<p class="text-sm text-muted m-0">
|
||||
{{ $t('assetBrowser.uploadModelDescription1') }}
|
||||
</p>
|
||||
<ul class="list-disc space-y-1 pl-5 mt-0 text-sm text-muted">
|
||||
<li>{{ $t('assetBrowser.uploadModelDescription2') }}</li>
|
||||
<li>{{ $t('assetBrowser.uploadModelDescription3') }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="text-sm text-muted mb-0">
|
||||
{{ $t('assetBrowser.civitaiLinkLabel') }}
|
||||
</label>
|
||||
<InputText
|
||||
v-model="url"
|
||||
:placeholder="$t('assetBrowser.civitaiLinkPlaceholder')"
|
||||
class="w-full"
|
||||
/>
|
||||
<p v-if="error" class="text-xs text-error">
|
||||
{{ error }}
|
||||
</p>
|
||||
<p v-else class="text-xs text-muted">
|
||||
{{ $t('assetBrowser.civitaiLinkExample') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import InputText from 'primevue/inputtext'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: string
|
||||
error?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
|
||||
const url = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value: string) => emit('update:modelValue', value)
|
||||
})
|
||||
</script>
|
||||
73
src/platform/assets/composables/useModelTypes.ts
Normal file
73
src/platform/assets/composables/useModelTypes.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { createSharedComposable, useAsyncState } from '@vueuse/core'
|
||||
|
||||
import { api } from '@/scripts/api'
|
||||
|
||||
/**
|
||||
* Format folder name to display name
|
||||
* Converts "upscale_models" -> "Upscale Models"
|
||||
* Converts "loras" -> "LoRAs"
|
||||
*/
|
||||
function formatDisplayName(folderName: string): string {
|
||||
// Special cases for acronyms and proper nouns
|
||||
const specialCases: Record<string, string> = {
|
||||
loras: 'LoRAs',
|
||||
ipadapter: 'IP-Adapter',
|
||||
sams: 'SAMs',
|
||||
clip_vision: 'CLIP Vision',
|
||||
animatediff_motion_lora: 'AnimateDiff Motion LoRA',
|
||||
animatediff_models: 'AnimateDiff Models',
|
||||
vae: 'VAE',
|
||||
sam2: 'SAM 2',
|
||||
controlnet: 'ControlNet',
|
||||
gligen: 'GLIGEN'
|
||||
}
|
||||
|
||||
if (specialCases[folderName]) {
|
||||
return specialCases[folderName]
|
||||
}
|
||||
|
||||
return folderName
|
||||
.split('_')
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
interface ModelTypeOption {
|
||||
name: string // Display name
|
||||
value: string // Actual tag value
|
||||
}
|
||||
|
||||
/**
|
||||
* Composable for fetching and managing model types from the API
|
||||
* Uses shared state to ensure data is only fetched once
|
||||
*/
|
||||
export const useModelTypes = createSharedComposable(() => {
|
||||
const {
|
||||
state: modelTypes,
|
||||
isLoading,
|
||||
error,
|
||||
execute: fetchModelTypes
|
||||
} = useAsyncState(
|
||||
async (): Promise<ModelTypeOption[]> => {
|
||||
const response = await api.getModelFolders()
|
||||
return response.map((folder) => ({
|
||||
name: formatDisplayName(folder.name),
|
||||
value: folder.name
|
||||
}))
|
||||
},
|
||||
[] as ModelTypeOption[],
|
||||
{
|
||||
immediate: false,
|
||||
onError: (err) => {
|
||||
console.error('Failed to fetch model types:', err)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
modelTypes,
|
||||
isLoading,
|
||||
error,
|
||||
fetchModelTypes
|
||||
}
|
||||
})
|
||||
184
src/platform/assets/composables/useUploadModelWizard.ts
Normal file
184
src/platform/assets/composables/useUploadModelWizard.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import type { Ref } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import { st } from '@/i18n'
|
||||
import type { AssetMetadata } from '@/platform/assets/schemas/assetSchema'
|
||||
import { assetService } from '@/platform/assets/services/assetService'
|
||||
|
||||
interface WizardData {
|
||||
url: string
|
||||
metadata: AssetMetadata | null
|
||||
name: string
|
||||
tags: string[]
|
||||
}
|
||||
|
||||
interface ModelTypeOption {
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export function useUploadModelWizard(modelTypes: Ref<ModelTypeOption[]>) {
|
||||
const currentStep = ref(1)
|
||||
const isFetchingMetadata = ref(false)
|
||||
const isUploading = ref(false)
|
||||
const uploadStatus = ref<'idle' | 'uploading' | 'success' | 'error'>('idle')
|
||||
const uploadError = ref('')
|
||||
|
||||
const wizardData = ref<WizardData>({
|
||||
url: '',
|
||||
metadata: null,
|
||||
name: '',
|
||||
tags: []
|
||||
})
|
||||
|
||||
const selectedModelType = ref<string | undefined>(undefined)
|
||||
|
||||
// Clear error when URL changes
|
||||
watch(
|
||||
() => wizardData.value.url,
|
||||
() => {
|
||||
uploadError.value = ''
|
||||
}
|
||||
)
|
||||
|
||||
// Validation
|
||||
const canFetchMetadata = computed(() => {
|
||||
return wizardData.value.url.trim().length > 0
|
||||
})
|
||||
|
||||
const canUploadModel = computed(() => {
|
||||
return !!selectedModelType.value
|
||||
})
|
||||
|
||||
function isCivitaiUrl(url: string): boolean {
|
||||
try {
|
||||
const hostname = new URL(url).hostname.toLowerCase()
|
||||
return hostname === 'civitai.com' || hostname.endsWith('.civitai.com')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchMetadata() {
|
||||
if (!canFetchMetadata.value) return
|
||||
|
||||
// Clean and normalize URL
|
||||
let cleanedUrl = wizardData.value.url.trim()
|
||||
try {
|
||||
cleanedUrl = new URL(encodeURI(cleanedUrl)).toString()
|
||||
} catch {
|
||||
// If URL parsing fails, just use the trimmed input
|
||||
}
|
||||
wizardData.value.url = cleanedUrl
|
||||
|
||||
if (!isCivitaiUrl(wizardData.value.url)) {
|
||||
uploadError.value = st(
|
||||
'assetBrowser.onlyCivitaiUrlsSupported',
|
||||
'Only Civitai URLs are supported'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
isFetchingMetadata.value = true
|
||||
try {
|
||||
const metadata = await assetService.getAssetMetadata(wizardData.value.url)
|
||||
wizardData.value.metadata = metadata
|
||||
|
||||
// Pre-fill name from metadata
|
||||
wizardData.value.name = metadata.filename || metadata.name || ''
|
||||
|
||||
// Pre-fill model type from metadata tags if available
|
||||
if (metadata.tags && metadata.tags.length > 0) {
|
||||
wizardData.value.tags = metadata.tags
|
||||
// Try to detect model type from tags
|
||||
const typeTag = metadata.tags.find((tag) =>
|
||||
modelTypes.value.some((type) => type.value === tag)
|
||||
)
|
||||
if (typeTag) {
|
||||
selectedModelType.value = typeTag
|
||||
}
|
||||
}
|
||||
|
||||
currentStep.value = 2
|
||||
} catch (error) {
|
||||
console.error('Failed to retrieve metadata:', error)
|
||||
uploadError.value =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: st(
|
||||
'assetBrowser.uploadModelFailedToRetrieveMetadata',
|
||||
'Failed to retrieve metadata. Please check the link and try again.'
|
||||
)
|
||||
currentStep.value = 1
|
||||
} finally {
|
||||
isFetchingMetadata.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadModel() {
|
||||
if (!canUploadModel.value) return
|
||||
|
||||
isUploading.value = true
|
||||
uploadStatus.value = 'uploading'
|
||||
|
||||
try {
|
||||
const tags = selectedModelType.value
|
||||
? ['models', selectedModelType.value]
|
||||
: ['models']
|
||||
const filename =
|
||||
wizardData.value.metadata?.filename ||
|
||||
wizardData.value.metadata?.name ||
|
||||
'model'
|
||||
|
||||
await assetService.uploadAssetFromUrl({
|
||||
url: wizardData.value.url,
|
||||
name: filename,
|
||||
tags,
|
||||
user_metadata: {
|
||||
source: 'civitai',
|
||||
source_url: wizardData.value.url,
|
||||
model_type: selectedModelType.value
|
||||
}
|
||||
})
|
||||
|
||||
uploadStatus.value = 'success'
|
||||
currentStep.value = 3
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('Failed to upload asset:', error)
|
||||
uploadStatus.value = 'error'
|
||||
uploadError.value =
|
||||
error instanceof Error ? error.message : 'Failed to upload model'
|
||||
currentStep.value = 3
|
||||
return false
|
||||
} finally {
|
||||
isUploading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goToPreviousStep() {
|
||||
if (currentStep.value > 1) {
|
||||
currentStep.value = currentStep.value - 1
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// State
|
||||
currentStep,
|
||||
isFetchingMetadata,
|
||||
isUploading,
|
||||
uploadStatus,
|
||||
uploadError,
|
||||
wizardData,
|
||||
selectedModelType,
|
||||
|
||||
// Computed
|
||||
canFetchMetadata,
|
||||
canUploadModel,
|
||||
|
||||
// Actions
|
||||
fetchMetadata,
|
||||
uploadModel,
|
||||
goToPreviousStep
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,29 @@ const zModelFile = z.object({
|
||||
pathIndex: z.number()
|
||||
})
|
||||
|
||||
const zValidationError = z.object({
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
field: z.string()
|
||||
})
|
||||
|
||||
const zValidationResult = z.object({
|
||||
is_valid: z.boolean(),
|
||||
errors: z.array(zValidationError).optional(),
|
||||
warnings: z.array(zValidationError).optional()
|
||||
})
|
||||
|
||||
const zAssetMetadata = z.object({
|
||||
content_length: z.number(),
|
||||
final_url: z.string(),
|
||||
content_type: z.string().optional(),
|
||||
filename: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
preview_url: z.string().optional(),
|
||||
validation: zValidationResult.optional()
|
||||
})
|
||||
|
||||
// Filename validation schema
|
||||
export const assetFilenameSchema = z
|
||||
.string()
|
||||
@@ -48,6 +71,7 @@ export const assetResponseSchema = zAssetResponse
|
||||
// Export types derived from Zod schemas
|
||||
export type AssetItem = z.infer<typeof zAsset>
|
||||
export type AssetResponse = z.infer<typeof zAssetResponse>
|
||||
export type AssetMetadata = z.infer<typeof zAssetMetadata>
|
||||
export type ModelFolder = z.infer<typeof zModelFolder>
|
||||
export type ModelFile = z.infer<typeof zModelFile>
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { fromZodError } from 'zod-validation-error'
|
||||
|
||||
import { st } from '@/i18n'
|
||||
import { assetResponseSchema } from '@/platform/assets/schemas/assetSchema'
|
||||
import type {
|
||||
AssetItem,
|
||||
AssetMetadata,
|
||||
AssetResponse,
|
||||
ModelFile,
|
||||
ModelFolder
|
||||
@@ -10,6 +12,36 @@ import type {
|
||||
import { api } from '@/scripts/api'
|
||||
import { useModelToNodeStore } from '@/stores/modelToNodeStore'
|
||||
|
||||
/**
|
||||
* Maps CivitAI validation error codes to localized error messages
|
||||
*/
|
||||
function getLocalizedErrorMessage(errorCode: string): string {
|
||||
const errorMessages: Record<string, string> = {
|
||||
FILE_TOO_LARGE: st('assetBrowser.errorFileTooLarge', 'File too large'),
|
||||
FORMAT_NOT_ALLOWED: st(
|
||||
'assetBrowser.errorFormatNotAllowed',
|
||||
'Format not allowed'
|
||||
),
|
||||
UNSAFE_PICKLE_SCAN: st(
|
||||
'assetBrowser.errorUnsafePickleScan',
|
||||
'Unsafe pickle scan'
|
||||
),
|
||||
UNSAFE_VIRUS_SCAN: st(
|
||||
'assetBrowser.errorUnsafeVirusScan',
|
||||
'Unsafe virus scan'
|
||||
),
|
||||
MODEL_TYPE_NOT_SUPPORTED: st(
|
||||
'assetBrowser.errorModelTypeNotSupported',
|
||||
'Model type not supported'
|
||||
)
|
||||
}
|
||||
return (
|
||||
errorMessages[errorCode] ||
|
||||
st('assetBrowser.errorUnknown', 'Unknown error') ||
|
||||
'Unknown error'
|
||||
)
|
||||
}
|
||||
|
||||
const ASSETS_ENDPOINT = '/assets'
|
||||
const EXPERIMENTAL_WARNING = `EXPERIMENTAL: If you are seeing this please make sure "Comfy.Assets.UseAssetAPI" is set to "false" in your ComfyUI Settings.\n`
|
||||
const DEFAULT_LIMIT = 500
|
||||
@@ -249,6 +281,77 @@ function createAssetService() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves metadata from a download URL without downloading the file
|
||||
*
|
||||
* @param url - Download URL to retrieve metadata from (will be URL-encoded)
|
||||
* @returns Promise with metadata including content_length, final_url, filename, etc.
|
||||
* @throws Error if metadata retrieval fails
|
||||
*/
|
||||
async function getAssetMetadata(url: string): Promise<AssetMetadata> {
|
||||
const encodedUrl = encodeURIComponent(url)
|
||||
const res = await api.fetchApi(
|
||||
`${ASSETS_ENDPOINT}/remote-metadata?url=${encodedUrl}`
|
||||
)
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({}))
|
||||
throw new Error(
|
||||
getLocalizedErrorMessage(errorData.code || 'UNKNOWN_ERROR')
|
||||
)
|
||||
}
|
||||
|
||||
const data: AssetMetadata = await res.json()
|
||||
if (data.validation?.is_valid === false) {
|
||||
throw new Error(
|
||||
getLocalizedErrorMessage(
|
||||
data.validation?.errors?.[0]?.code || 'UNKNOWN_ERROR'
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads an asset by providing a URL to download from
|
||||
*
|
||||
* @param params - Upload parameters
|
||||
* @param params.url - HTTP/HTTPS URL to download from
|
||||
* @param params.name - Display name (determines extension)
|
||||
* @param params.tags - Optional freeform tags
|
||||
* @param params.user_metadata - Optional custom metadata object
|
||||
* @param params.preview_id - Optional UUID for preview asset
|
||||
* @returns Promise<AssetItem & { created_new: boolean }> - Asset object with created_new flag
|
||||
* @throws Error if upload fails
|
||||
*/
|
||||
async function uploadAssetFromUrl(params: {
|
||||
url: string
|
||||
name: string
|
||||
tags?: string[]
|
||||
user_metadata?: Record<string, any>
|
||||
preview_id?: string
|
||||
}): Promise<AssetItem & { created_new: boolean }> {
|
||||
const res = await api.fetchApi(ASSETS_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(params)
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
st(
|
||||
'assetBrowser.errorUploadFailed',
|
||||
'Failed to upload asset. Please try again.'
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return await res.json()
|
||||
}
|
||||
|
||||
return {
|
||||
getAssetModelFolders,
|
||||
getAssetModels,
|
||||
@@ -256,7 +359,9 @@ function createAssetService() {
|
||||
getAssetsForNodeType,
|
||||
getAssetDetails,
|
||||
getAssetsByTag,
|
||||
deleteAsset
|
||||
deleteAsset,
|
||||
getAssetMetadata,
|
||||
uploadAssetFromUrl
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -107,10 +107,17 @@ const {
|
||||
|
||||
const authActions = useFirebaseAuthActions()
|
||||
|
||||
// Get max sortOrder from settings in a group
|
||||
const getGroupSortOrder = (group: SettingTreeNode): number =>
|
||||
Math.max(0, ...flattenTree<SettingParams>(group).map((s) => s.sortOrder ?? 0))
|
||||
|
||||
// Sort groups for a category
|
||||
const sortedGroups = (category: SettingTreeNode): ISettingGroup[] => {
|
||||
return [...(category.children ?? [])]
|
||||
.sort((a, b) => a.label.localeCompare(b.label))
|
||||
.sort((a, b) => {
|
||||
const orderDiff = getGroupSortOrder(b) - getGroupSortOrder(a)
|
||||
return orderDiff !== 0 ? orderDiff : a.label.localeCompare(b.label)
|
||||
})
|
||||
.map((group) => ({
|
||||
label: group.label,
|
||||
settings: flattenTree<SettingParams>(group).sort((a, b) => {
|
||||
|
||||
@@ -1082,24 +1082,28 @@ export const CORE_SETTINGS: SettingParams[] = [
|
||||
},
|
||||
|
||||
/**
|
||||
* Vue Node System Settings
|
||||
* Nodes 2.0 Settings
|
||||
*/
|
||||
{
|
||||
id: 'Comfy.VueNodes.Enabled',
|
||||
name: 'Modern Node Design (Vue Nodes)',
|
||||
category: ['Comfy', 'Nodes 2.0', 'VueNodesEnabled'],
|
||||
name: 'Modern Node Design (Nodes 2.0)',
|
||||
type: 'boolean',
|
||||
tooltip:
|
||||
'Modern: DOM-based rendering with enhanced interactivity, native browser features, and updated visual design. Classic: Traditional canvas rendering.',
|
||||
defaultValue: false,
|
||||
sortOrder: 100,
|
||||
experimental: true,
|
||||
versionAdded: '1.27.1'
|
||||
},
|
||||
{
|
||||
id: 'Comfy.VueNodes.AutoScaleLayout',
|
||||
name: 'Auto-scale layout (Vue nodes)',
|
||||
category: ['Comfy', 'Nodes 2.0', 'AutoScaleLayout'],
|
||||
name: 'Auto-scale layout (Nodes 2.0)',
|
||||
tooltip:
|
||||
'Automatically scale node positions when switching to Vue rendering to prevent overlap',
|
||||
type: 'boolean',
|
||||
sortOrder: 50,
|
||||
experimental: true,
|
||||
defaultValue: true,
|
||||
versionAdded: '1.30.3'
|
||||
|
||||
@@ -38,8 +38,9 @@ function onChange(
|
||||
}
|
||||
// Backward compatibility with old settings dialog.
|
||||
// Some extensions still listens event emitted by the old settings dialog.
|
||||
// @ts-expect-error 'setting' is possibly 'undefined'.ts(18048)
|
||||
app.ui.settings.dispatchChange(setting.id, newValue, oldValue)
|
||||
if (setting) {
|
||||
app.ui.settings.dispatchChange(setting.id, newValue, oldValue)
|
||||
}
|
||||
}
|
||||
|
||||
export const useSettingStore = defineStore('setting', () => {
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { InjectionKey } from 'vue'
|
||||
|
||||
import type { useTransformState } from '@/renderer/core/layout/transform/useTransformState'
|
||||
|
||||
/**
|
||||
* Lightweight, injectable transform state used by layout-aware components.
|
||||
*
|
||||
* Consumers use this interface to convert coordinates between LiteGraph's
|
||||
* canvas space and the DOM's screen space, access the current pan/zoom
|
||||
* (camera), and perform basic viewport culling checks.
|
||||
*
|
||||
* Coordinate mapping:
|
||||
* - screen = (canvas + offset) * scale
|
||||
* - canvas = screen / scale - offset
|
||||
*
|
||||
* The full implementation and additional helpers live in
|
||||
* `useTransformState()`. This interface deliberately exposes only the
|
||||
* minimal surface needed outside that composable.
|
||||
*
|
||||
* @example
|
||||
* const state = inject(TransformStateKey)!
|
||||
* const screen = state.canvasToScreen({ x: 100, y: 50 })
|
||||
*/
|
||||
export interface TransformState
|
||||
extends Pick<
|
||||
ReturnType<typeof useTransformState>,
|
||||
'screenToCanvas' | 'canvasToScreen' | 'camera' | 'isNodeInViewport'
|
||||
> {}
|
||||
|
||||
export const TransformStateKey: InjectionKey<TransformState> =
|
||||
Symbol('transformState')
|
||||
@@ -17,10 +17,9 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useRafFn } from '@vueuse/core'
|
||||
import { computed, provide } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import type { LGraphCanvas } from '@/lib/litegraph/src/litegraph'
|
||||
import { TransformStateKey } from '@/renderer/core/layout/injectionKeys'
|
||||
import { useTransformSettling } from '@/renderer/core/layout/transform/useTransformSettling'
|
||||
import { useTransformState } from '@/renderer/core/layout/transform/useTransformState'
|
||||
import { useLOD } from '@/renderer/extensions/vueNodes/lod/useLOD'
|
||||
@@ -32,14 +31,7 @@ interface TransformPaneProps {
|
||||
|
||||
const props = defineProps<TransformPaneProps>()
|
||||
|
||||
const {
|
||||
camera,
|
||||
transformStyle,
|
||||
syncWithCanvas,
|
||||
canvasToScreen,
|
||||
screenToCanvas,
|
||||
isNodeInViewport
|
||||
} = useTransformState()
|
||||
const { camera, transformStyle, syncWithCanvas } = useTransformState()
|
||||
|
||||
const { isLOD } = useLOD(camera)
|
||||
|
||||
@@ -48,13 +40,6 @@ const { isTransforming: isInteracting } = useTransformSettling(canvasElement, {
|
||||
settleDelay: 512
|
||||
})
|
||||
|
||||
provide(TransformStateKey, {
|
||||
camera,
|
||||
canvasToScreen,
|
||||
screenToCanvas,
|
||||
isNodeInViewport
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
transformUpdate: []
|
||||
}>()
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
import { computed, reactive, readonly } from 'vue'
|
||||
|
||||
import type { LGraphCanvas } from '@/lib/litegraph/src/litegraph'
|
||||
import { createSharedComposable } from '@vueuse/core'
|
||||
|
||||
interface Point {
|
||||
x: number
|
||||
@@ -64,7 +65,7 @@ interface Camera {
|
||||
z: number // scale/zoom
|
||||
}
|
||||
|
||||
export const useTransformState = () => {
|
||||
function useTransformStateIndividual() {
|
||||
// Reactive state mirroring LiteGraph's canvas transform
|
||||
const camera = reactive<Camera>({
|
||||
x: 0,
|
||||
@@ -91,7 +92,7 @@ export const useTransformState = () => {
|
||||
*
|
||||
* @param canvas - LiteGraph canvas instance with DragAndScale (ds) transform state
|
||||
*/
|
||||
const syncWithCanvas = (canvas: LGraphCanvas) => {
|
||||
function syncWithCanvas(canvas: LGraphCanvas) {
|
||||
if (!canvas || !canvas.ds) return
|
||||
|
||||
// Mirror LiteGraph's transform state to Vue's reactive state
|
||||
@@ -112,7 +113,7 @@ export const useTransformState = () => {
|
||||
* @param point - Point in canvas coordinate system
|
||||
* @returns Point in screen coordinate system
|
||||
*/
|
||||
const canvasToScreen = (point: Point): Point => {
|
||||
function canvasToScreen(point: Point): Point {
|
||||
return {
|
||||
x: (point.x + camera.x) * camera.z,
|
||||
y: (point.y + camera.y) * camera.z
|
||||
@@ -138,10 +139,10 @@ export const useTransformState = () => {
|
||||
}
|
||||
|
||||
// Get node's screen bounds for culling
|
||||
const getNodeScreenBounds = (
|
||||
pos: ArrayLike<number>,
|
||||
size: ArrayLike<number>
|
||||
): DOMRect => {
|
||||
function getNodeScreenBounds(
|
||||
pos: [number, number],
|
||||
size: [number, number]
|
||||
): DOMRect {
|
||||
const topLeft = canvasToScreen({ x: pos[0], y: pos[1] })
|
||||
const width = size[0] * camera.z
|
||||
const height = size[1] * camera.z
|
||||
@@ -150,23 +151,23 @@ export const useTransformState = () => {
|
||||
}
|
||||
|
||||
// Helper: Calculate zoom-adjusted margin for viewport culling
|
||||
const calculateAdjustedMargin = (baseMargin: number): number => {
|
||||
function calculateAdjustedMargin(baseMargin: number): number {
|
||||
if (camera.z < 0.1) return Math.min(baseMargin * 5, 2.0)
|
||||
if (camera.z > 3.0) return Math.max(baseMargin * 0.5, 0.05)
|
||||
return baseMargin
|
||||
}
|
||||
|
||||
// Helper: Check if node is too small to be visible at current zoom
|
||||
const isNodeTooSmall = (nodeSize: ArrayLike<number>): boolean => {
|
||||
function isNodeTooSmall(nodeSize: [number, number]): boolean {
|
||||
const nodeScreenSize = Math.max(nodeSize[0], nodeSize[1]) * camera.z
|
||||
return nodeScreenSize < 4
|
||||
}
|
||||
|
||||
// Helper: Calculate expanded viewport bounds with margin
|
||||
const getExpandedViewportBounds = (
|
||||
function getExpandedViewportBounds(
|
||||
viewport: { width: number; height: number },
|
||||
margin: number
|
||||
) => {
|
||||
) {
|
||||
const marginX = viewport.width * margin
|
||||
const marginY = viewport.height * margin
|
||||
return {
|
||||
@@ -178,11 +179,11 @@ export const useTransformState = () => {
|
||||
}
|
||||
|
||||
// Helper: Test if node intersects with viewport bounds
|
||||
const testViewportIntersection = (
|
||||
function testViewportIntersection(
|
||||
screenPos: { x: number; y: number },
|
||||
nodeSize: ArrayLike<number>,
|
||||
nodeSize: [number, number],
|
||||
bounds: { left: number; right: number; top: number; bottom: number }
|
||||
): boolean => {
|
||||
): boolean {
|
||||
const nodeRight = screenPos.x + nodeSize[0] * camera.z
|
||||
const nodeBottom = screenPos.y + nodeSize[1] * camera.z
|
||||
|
||||
@@ -195,12 +196,12 @@ export const useTransformState = () => {
|
||||
}
|
||||
|
||||
// Check if node is within viewport with frustum and size-based culling
|
||||
const isNodeInViewport = (
|
||||
nodePos: ArrayLike<number>,
|
||||
nodeSize: ArrayLike<number>,
|
||||
function isNodeInViewport(
|
||||
nodePos: [number, number],
|
||||
nodeSize: [number, number],
|
||||
viewport: { width: number; height: number },
|
||||
margin: number = 0.2
|
||||
): boolean => {
|
||||
): boolean {
|
||||
// Early exit for tiny nodes
|
||||
if (isNodeTooSmall(nodeSize)) return false
|
||||
|
||||
@@ -212,10 +213,10 @@ export const useTransformState = () => {
|
||||
}
|
||||
|
||||
// Get viewport bounds in canvas coordinates (for spatial index queries)
|
||||
const getViewportBounds = (
|
||||
function getViewportBounds(
|
||||
viewport: { width: number; height: number },
|
||||
margin: number = 0.2
|
||||
) => {
|
||||
) {
|
||||
const marginX = viewport.width * margin
|
||||
const marginY = viewport.height * margin
|
||||
|
||||
@@ -244,3 +245,7 @@ export const useTransformState = () => {
|
||||
getViewportBounds
|
||||
}
|
||||
}
|
||||
|
||||
export const useTransformState = createSharedComposable(
|
||||
useTransformStateIndividual
|
||||
)
|
||||
|
||||
@@ -11,9 +11,9 @@ interface SpatialBounds {
|
||||
height: number
|
||||
}
|
||||
|
||||
interface PositionedNode {
|
||||
pos: ArrayLike<number>
|
||||
size: ArrayLike<number>
|
||||
export interface PositionedNode {
|
||||
pos: [number, number]
|
||||
size: [number, number]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { LGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { calculateNodeBounds } from '@/renderer/core/spatial/boundsCalculator'
|
||||
import type { PositionedNode } from '@/renderer/core/spatial/boundsCalculator'
|
||||
|
||||
import type {
|
||||
IMinimapDataSource,
|
||||
@@ -29,10 +30,12 @@ export abstract class AbstractMinimapDataSource implements IMinimapDataSource {
|
||||
}
|
||||
|
||||
// Convert MinimapNodeData to the format expected by calculateNodeBounds
|
||||
const compatibleNodes = nodes.map((node) => ({
|
||||
pos: [node.x, node.y],
|
||||
size: [node.width, node.height]
|
||||
}))
|
||||
const compatibleNodes = nodes.map(
|
||||
(node): PositionedNode => ({
|
||||
pos: [node.x, node.y],
|
||||
size: [node.width, node.height]
|
||||
})
|
||||
)
|
||||
|
||||
const bounds = calculateNodeBounds(compatibleNodes)
|
||||
if (!bounds) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<SlotConnectionDot
|
||||
ref="connectionDotRef"
|
||||
:color="slotColor"
|
||||
:class="cn('-translate-x-1/2', 'w-3', errorClassesDot)"
|
||||
:class="cn('-translate-x-1/2 w-3', errorClassesDot)"
|
||||
@pointerdown="onPointerDown"
|
||||
/>
|
||||
|
||||
@@ -48,6 +48,7 @@ interface InputSlotProps {
|
||||
connected?: boolean
|
||||
compatible?: boolean
|
||||
dotOnly?: boolean
|
||||
socketless?: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<InputSlotProps>()
|
||||
@@ -121,7 +122,8 @@ const slotWrapperClass = computed(() =>
|
||||
'lg-slot--connected': props.connected,
|
||||
'lg-slot--compatible': props.compatible,
|
||||
'opacity-40': shouldDim.value
|
||||
}
|
||||
},
|
||||
props.socketless && 'pointer-events-none invisible'
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
'outline-transparent outline-2',
|
||||
borderClass,
|
||||
outlineClass,
|
||||
cursorClass,
|
||||
{
|
||||
'before:rounded-2xl before:pointer-events-none before:absolute before:bg-bypass/60 before:inset-0':
|
||||
bypassed,
|
||||
'before:rounded-2xl before:pointer-events-none before:absolute before:inset-0':
|
||||
muted,
|
||||
'will-change-transform': isDragging,
|
||||
'ring-4 ring-primary-500 bg-primary-500/10': isDraggingOver
|
||||
},
|
||||
|
||||
@@ -39,10 +39,10 @@
|
||||
zIndex: zIndex,
|
||||
opacity: nodeOpacity,
|
||||
'--component-node-background': nodeBodyBackgroundColor
|
||||
},
|
||||
dragStyle
|
||||
}
|
||||
]"
|
||||
v-bind="pointerHandlers"
|
||||
v-bind="remainingPointerHandlers"
|
||||
@pointerdown="nodeOnPointerdown"
|
||||
@wheel="handleWheel"
|
||||
@contextmenu="handleContextMenu"
|
||||
@dragover.prevent="handleDragOver"
|
||||
@@ -137,24 +137,30 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, inject, onErrorCaptured, onMounted, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onErrorCaptured, onMounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import type { VueNodeData } from '@/composables/graph/useGraphNodeManager'
|
||||
import { toggleNodeOptions } from '@/composables/graph/useMoreOptionsMenu'
|
||||
import { useErrorHandling } from '@/composables/useErrorHandling'
|
||||
import { st } from '@/i18n'
|
||||
import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import {
|
||||
LGraphCanvas,
|
||||
LGraphEventMode,
|
||||
LiteGraph
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { useTelemetry } from '@/platform/telemetry'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import { useCanvasInteractions } from '@/renderer/core/canvas/useCanvasInteractions'
|
||||
import { TransformStateKey } from '@/renderer/core/layout/injectionKeys'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import SlotConnectionDot from '@/renderer/extensions/vueNodes/components/SlotConnectionDot.vue'
|
||||
import { useNodeEventHandlers } from '@/renderer/extensions/vueNodes/composables/useNodeEventHandlers'
|
||||
import { useNodePointerInteractions } from '@/renderer/extensions/vueNodes/composables/useNodePointerInteractions'
|
||||
import { useNodeZIndex } from '@/renderer/extensions/vueNodes/composables/useNodeZIndex'
|
||||
import { useVueElementTracking } from '@/renderer/extensions/vueNodes/composables/useVueNodeResizeTracking'
|
||||
import { useNodeExecutionState } from '@/renderer/extensions/vueNodes/execution/useNodeExecutionState'
|
||||
import { useNodeDrag } from '@/renderer/extensions/vueNodes/layout/useNodeDrag'
|
||||
import { useNodeLayout } from '@/renderer/extensions/vueNodes/layout/useNodeLayout'
|
||||
import { useNodePreviewState } from '@/renderer/extensions/vueNodes/preview/useNodePreviewState'
|
||||
import { nonWidgetedInputs } from '@/renderer/extensions/vueNodes/utils/nodeDataUtils'
|
||||
@@ -188,22 +194,12 @@ const { nodeData, error = null } = defineProps<LGraphNodeProps>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const {
|
||||
handleNodeCollapse,
|
||||
handleNodeTitleUpdate,
|
||||
handleNodeSelect,
|
||||
handleNodeRightClick
|
||||
} = useNodeEventHandlers()
|
||||
const { handleNodeCollapse, handleNodeTitleUpdate, handleNodeRightClick } =
|
||||
useNodeEventHandlers()
|
||||
const { bringNodeToFront } = useNodeZIndex()
|
||||
|
||||
useVueElementTracking(() => nodeData.id, 'node')
|
||||
|
||||
const transformState = inject(TransformStateKey)
|
||||
if (!transformState) {
|
||||
throw new Error(
|
||||
'TransformState must be provided for node resize functionality'
|
||||
)
|
||||
}
|
||||
|
||||
const { selectedNodeIds } = storeToRefs(useCanvasStore())
|
||||
const isSelected = computed(() => {
|
||||
return selectedNodeIds.value.has(nodeData.id)
|
||||
@@ -272,10 +268,24 @@ onErrorCaptured((error) => {
|
||||
})
|
||||
|
||||
const { position, size, zIndex, moveNodeTo } = useNodeLayout(() => nodeData.id)
|
||||
const { pointerHandlers, isDragging, dragStyle } = useNodePointerInteractions(
|
||||
() => nodeData,
|
||||
handleNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions(() => nodeData.id)
|
||||
const { onPointerdown, ...remainingPointerHandlers } = pointerHandlers
|
||||
const { startDrag } = useNodeDrag()
|
||||
|
||||
async function nodeOnPointerdown(event: PointerEvent) {
|
||||
if (event.altKey && lgraphNode.value) {
|
||||
const result = LGraphCanvas.cloneNodes([lgraphNode.value])
|
||||
if (result?.created?.length) {
|
||||
const [newNode] = result.created
|
||||
startDrag(event, `${newNode.id}`)
|
||||
layoutStore.isDraggingVueNodes.value = true
|
||||
await nextTick()
|
||||
bringNodeToFront(`${newNode.id}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
onPointerdown(event)
|
||||
}
|
||||
|
||||
// Handle right-click context menu
|
||||
const handleContextMenu = (event: MouseEvent) => {
|
||||
@@ -283,7 +293,7 @@ const handleContextMenu = (event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
|
||||
// First handle the standard right-click behavior (selection)
|
||||
handleNodeRightClick(event as PointerEvent, nodeData)
|
||||
handleNodeRightClick(event as PointerEvent, nodeData.id)
|
||||
|
||||
// Show the node options menu at the cursor position
|
||||
const targetElement = event.currentTarget as HTMLElement
|
||||
@@ -346,29 +356,24 @@ const cornerResizeHandles: CornerResizeHandle[] = [
|
||||
|
||||
const MIN_NODE_WIDTH = 225
|
||||
|
||||
const { startResize } = useNodeResize(
|
||||
(result, element) => {
|
||||
if (isCollapsed.value) return
|
||||
const { startResize } = useNodeResize((result, element) => {
|
||||
if (isCollapsed.value) return
|
||||
|
||||
// Clamp width to minimum to avoid conflicts with CSS min-width
|
||||
const clampedWidth = Math.max(result.size.width, MIN_NODE_WIDTH)
|
||||
// Clamp width to minimum to avoid conflicts with CSS min-width
|
||||
const clampedWidth = Math.max(result.size.width, MIN_NODE_WIDTH)
|
||||
|
||||
// Apply size directly to DOM element - ResizeObserver will pick this up
|
||||
element.style.setProperty('--node-width', `${clampedWidth}px`)
|
||||
element.style.setProperty('--node-height', `${result.size.height}px`)
|
||||
// Apply size directly to DOM element - ResizeObserver will pick this up
|
||||
element.style.setProperty('--node-width', `${clampedWidth}px`)
|
||||
element.style.setProperty('--node-height', `${result.size.height}px`)
|
||||
|
||||
const currentPosition = position.value
|
||||
const deltaX = Math.abs(result.position.x - currentPosition.x)
|
||||
const deltaY = Math.abs(result.position.y - currentPosition.y)
|
||||
const currentPosition = position.value
|
||||
const deltaX = Math.abs(result.position.x - currentPosition.x)
|
||||
const deltaY = Math.abs(result.position.y - currentPosition.y)
|
||||
|
||||
if (deltaX > POSITION_EPSILON || deltaY > POSITION_EPSILON) {
|
||||
moveNodeTo(result.position)
|
||||
}
|
||||
},
|
||||
{
|
||||
transformState
|
||||
if (deltaX > POSITION_EPSILON || deltaY > POSITION_EPSILON) {
|
||||
moveNodeTo(result.position)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
const handleResizePointerDown = (direction: ResizeHandleDirection) => {
|
||||
return (event: PointerEvent) => {
|
||||
@@ -422,6 +427,16 @@ const outlineClass = computed(() => {
|
||||
)
|
||||
})
|
||||
|
||||
const cursorClass = computed(() => {
|
||||
return cn(
|
||||
nodeData.flags?.pinned
|
||||
? 'cursor-default'
|
||||
: layoutStore.isDraggingVueNodes.value
|
||||
? 'cursor-grabbing'
|
||||
: 'cursor-grab'
|
||||
)
|
||||
})
|
||||
|
||||
// Event handlers
|
||||
const handleCollapse = () => {
|
||||
handleNodeCollapse(nodeData.id, !isCollapsed.value)
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
}"
|
||||
:node-id="nodeData?.id != null ? String(nodeData.id) : ''"
|
||||
:index="widget.slotMetadata.index"
|
||||
:socketless="widget.simplified.spec?.socketless"
|
||||
dot-only
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -10,12 +10,12 @@
|
||||
*/
|
||||
import { createSharedComposable } from '@vueuse/core'
|
||||
|
||||
import type { VueNodeData } from '@/composables/graph/useGraphNodeManager'
|
||||
import { useVueNodeLifecycle } from '@/composables/graph/useVueNodeLifecycle'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import { useCanvasInteractions } from '@/renderer/core/canvas/useCanvasInteractions'
|
||||
import { useNodeZIndex } from '@/renderer/extensions/vueNodes/composables/useNodeZIndex'
|
||||
import { isMultiSelectKey } from '@/renderer/extensions/vueNodes/utils/selectionUtils'
|
||||
import type { NodeId } from '@/renderer/core/layout/types'
|
||||
|
||||
function useNodeEventHandlersIndividual() {
|
||||
const canvasStore = useCanvasStore()
|
||||
@@ -27,12 +27,12 @@ function useNodeEventHandlersIndividual() {
|
||||
* Handle node selection events
|
||||
* Supports single selection and multi-select with Ctrl/Cmd
|
||||
*/
|
||||
const handleNodeSelect = (event: PointerEvent, nodeData: VueNodeData) => {
|
||||
function handleNodeSelect(event: PointerEvent, nodeId: NodeId) {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
|
||||
const node = nodeManager.value.getNode(nodeData.id)
|
||||
const node = nodeManager.value.getNode(nodeId)
|
||||
if (!node) return
|
||||
|
||||
const multiSelect = isMultiSelectKey(event)
|
||||
@@ -53,7 +53,7 @@ function useNodeEventHandlersIndividual() {
|
||||
// Bring node to front when clicked (similar to LiteGraph behavior)
|
||||
// Skip if node is pinned to avoid unwanted movement
|
||||
if (!node.flags?.pinned) {
|
||||
bringNodeToFront(nodeData.id)
|
||||
bringNodeToFront(nodeId)
|
||||
}
|
||||
|
||||
// Update canvas selection tracking
|
||||
@@ -64,7 +64,7 @@ function useNodeEventHandlersIndividual() {
|
||||
* Handle node collapse/expand state changes
|
||||
* Uses LiteGraph's native collapse method for proper state management
|
||||
*/
|
||||
const handleNodeCollapse = (nodeId: string, collapsed: boolean) => {
|
||||
function handleNodeCollapse(nodeId: NodeId, collapsed: boolean) {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!nodeManager.value) return
|
||||
@@ -83,7 +83,7 @@ function useNodeEventHandlersIndividual() {
|
||||
* Handle node title updates
|
||||
* Updates the title in LiteGraph for persistence across sessions
|
||||
*/
|
||||
const handleNodeTitleUpdate = (nodeId: string, newTitle: string) => {
|
||||
function handleNodeTitleUpdate(nodeId: NodeId, newTitle: string) {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!nodeManager.value) return
|
||||
@@ -95,41 +95,16 @@ function useNodeEventHandlersIndividual() {
|
||||
node.title = newTitle
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle node double-click events
|
||||
* Can be used for custom actions like opening node editor
|
||||
*/
|
||||
const handleNodeDoubleClick = (
|
||||
event: PointerEvent,
|
||||
nodeData: VueNodeData
|
||||
) => {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
|
||||
const node = nodeManager.value.getNode(nodeData.id)
|
||||
if (!node) return
|
||||
|
||||
// Prevent default browser behavior
|
||||
event.preventDefault()
|
||||
|
||||
// TODO: add custom double-click behavior here
|
||||
// For now, ensure node is selected
|
||||
if (!node.selected) {
|
||||
handleNodeSelect(event, nodeData)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle node right-click context menu events
|
||||
* Integrates with LiteGraph's context menu system
|
||||
*/
|
||||
const handleNodeRightClick = (event: PointerEvent, nodeData: VueNodeData) => {
|
||||
function handleNodeRightClick(event: PointerEvent, nodeId: NodeId) {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
|
||||
const node = nodeManager.value.getNode(nodeData.id)
|
||||
const node = nodeManager.value.getNode(nodeId)
|
||||
if (!node) return
|
||||
|
||||
// Prevent default context menu
|
||||
@@ -137,128 +112,17 @@ function useNodeEventHandlersIndividual() {
|
||||
|
||||
// Select the node if not already selected
|
||||
if (!node.selected) {
|
||||
handleNodeSelect(event, nodeData)
|
||||
handleNodeSelect(event, nodeId)
|
||||
}
|
||||
|
||||
// Let LiteGraph handle the context menu
|
||||
// The canvas will handle showing the appropriate context menu
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle node drag start events
|
||||
* Prepares node for dragging and sets appropriate visual state
|
||||
*/
|
||||
const handleNodeDragStart = (event: DragEvent, nodeData: VueNodeData) => {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
|
||||
const node = nodeManager.value.getNode(nodeData.id)
|
||||
if (!node) return
|
||||
|
||||
// Ensure node is selected before dragging
|
||||
if (!node.selected) {
|
||||
// Create a synthetic pointer event for selection
|
||||
const syntheticEvent = new PointerEvent('pointerdown', {
|
||||
ctrlKey: event.ctrlKey,
|
||||
metaKey: event.metaKey,
|
||||
bubbles: true
|
||||
})
|
||||
handleNodeSelect(syntheticEvent, nodeData)
|
||||
}
|
||||
|
||||
// Set drag data for potential drop operations
|
||||
if (event.dataTransfer) {
|
||||
event.dataTransfer.setData('application/comfy-node-id', nodeData.id)
|
||||
event.dataTransfer.effectAllowed = 'move'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Batch select multiple nodes
|
||||
* Useful for selection toolbox or area selection
|
||||
*/
|
||||
const selectNodes = (nodeIds: string[], addToSelection = false) => {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
|
||||
if (!addToSelection) {
|
||||
canvasStore.canvas.deselectAll()
|
||||
}
|
||||
|
||||
nodeIds.forEach((nodeId) => {
|
||||
const node = nodeManager.value?.getNode(nodeId)
|
||||
if (node && canvasStore.canvas) {
|
||||
canvasStore.canvas.select(node)
|
||||
}
|
||||
})
|
||||
|
||||
canvasStore.updateSelectedItems()
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure node is selected for shift-drag operations
|
||||
* Handles special logic for promoting a node to selection when shift-dragging
|
||||
* @param event - The pointer event (for multi-select key detection)
|
||||
* @param nodeData - The node data for the node being dragged
|
||||
* @param wasSelectedAtPointerDown - Whether the node was selected when pointer-down occurred
|
||||
*/
|
||||
const ensureNodeSelectedForShiftDrag = (
|
||||
event: PointerEvent,
|
||||
nodeData: VueNodeData,
|
||||
wasSelectedAtPointerDown: boolean
|
||||
) => {
|
||||
if (wasSelectedAtPointerDown) return
|
||||
|
||||
const multiSelectKeyPressed = isMultiSelectKey(event)
|
||||
if (!multiSelectKeyPressed) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
const node = nodeManager.value.getNode(nodeData.id)
|
||||
if (!node || node.selected) return
|
||||
|
||||
const selectionCount = canvasStore.selectedItems.length
|
||||
const addToSelection = selectionCount > 0
|
||||
selectNodes([nodeData.id], addToSelection)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deselect specific nodes
|
||||
*/
|
||||
const deselectNodes = (nodeIds: string[]) => {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
|
||||
nodeIds.forEach((nodeId) => {
|
||||
const node = nodeManager.value?.getNode(nodeId)
|
||||
if (node && canvasStore.canvas) {
|
||||
canvasStore.canvas.deselect(node)
|
||||
}
|
||||
})
|
||||
|
||||
canvasStore.updateSelectedItems()
|
||||
}
|
||||
|
||||
const deselectNode = (nodeId: string) => {
|
||||
const node = nodeManager.value?.getNode(nodeId)
|
||||
if (node) {
|
||||
canvasStore.canvas?.deselect(node)
|
||||
canvasStore.updateSelectedItems()
|
||||
}
|
||||
}
|
||||
|
||||
const toggleNodeSelectionAfterPointerUp = (
|
||||
nodeId: string,
|
||||
{
|
||||
wasSelectedAtPointerDown,
|
||||
multiSelect
|
||||
}: {
|
||||
wasSelectedAtPointerDown: boolean
|
||||
multiSelect: boolean
|
||||
}
|
||||
) => {
|
||||
function toggleNodeSelectionAfterPointerUp(
|
||||
nodeId: NodeId,
|
||||
multiSelect: boolean
|
||||
) {
|
||||
if (!shouldHandleNodePointerEvents.value) return
|
||||
|
||||
if (!canvasStore.canvas || !nodeManager.value) return
|
||||
@@ -267,22 +131,19 @@ function useNodeEventHandlersIndividual() {
|
||||
if (!node) return
|
||||
|
||||
if (!multiSelect) {
|
||||
const multipleSelected = canvasStore.selectedItems.length > 1
|
||||
if (multipleSelected && wasSelectedAtPointerDown) {
|
||||
canvasStore.canvas.deselectAll()
|
||||
canvasStore.canvas.select(node)
|
||||
canvasStore.updateSelectedItems()
|
||||
}
|
||||
canvasStore.canvas.deselectAll()
|
||||
canvasStore.canvas.select(node)
|
||||
canvasStore.updateSelectedItems()
|
||||
return
|
||||
}
|
||||
|
||||
if (wasSelectedAtPointerDown) {
|
||||
if (node.selected) {
|
||||
canvasStore.canvas.deselect(node)
|
||||
canvasStore.updateSelectedItems()
|
||||
} else {
|
||||
canvasStore.canvas.select(node)
|
||||
}
|
||||
|
||||
// No action needed when the node was not previously selected since the pointer-down
|
||||
// handler already added it to the selection.
|
||||
canvasStore.updateSelectedItems()
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -290,15 +151,9 @@ function useNodeEventHandlersIndividual() {
|
||||
handleNodeSelect,
|
||||
handleNodeCollapse,
|
||||
handleNodeTitleUpdate,
|
||||
handleNodeDoubleClick,
|
||||
handleNodeRightClick,
|
||||
handleNodeDragStart,
|
||||
|
||||
// Batch operations
|
||||
selectNodes,
|
||||
deselectNodes,
|
||||
deselectNode,
|
||||
ensureNodeSelectedForShiftDrag,
|
||||
toggleNodeSelectionAfterPointerUp
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { setActivePinia } from 'pinia'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { nextTick, ref } from 'vue'
|
||||
|
||||
import type { VueNodeData } from '@/composables/graph/useGraphNodeManager'
|
||||
import { useNodePointerInteractions } from '@/renderer/extensions/vueNodes/composables/useNodePointerInteractions'
|
||||
import { useNodeEventHandlers } from '@/renderer/extensions/vueNodes/composables/useNodeEventHandlers'
|
||||
import { createTestingPinia } from '@pinia/testing'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import type { NodeLayout } from '@/renderer/core/layout/types'
|
||||
import { useNodeDrag } from '@/renderer/extensions/vueNodes/layout/useNodeDrag'
|
||||
|
||||
const forwardEventToCanvasMock = vi.fn()
|
||||
const deselectNodeMock = vi.fn()
|
||||
const selectNodesMock = vi.fn()
|
||||
const toggleNodeSelectionAfterPointerUpMock = vi.fn()
|
||||
const ensureNodeSelectedForShiftDragMock = vi.fn()
|
||||
const selectedItemsState: { items: Array<{ id?: string }> } = { items: [] }
|
||||
|
||||
// Mock the dependencies
|
||||
@@ -20,19 +20,18 @@ vi.mock('@/renderer/core/canvas/useCanvasInteractions', () => ({
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/renderer/extensions/vueNodes/layout/useNodeLayout', () => ({
|
||||
useNodeLayout: () => ({
|
||||
startDrag: vi.fn(),
|
||||
endDrag: vi.fn().mockResolvedValue(undefined),
|
||||
handleDrag: vi.fn().mockResolvedValue(undefined)
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/renderer/core/layout/store/layoutStore', () => ({
|
||||
layoutStore: {
|
||||
isDraggingVueNodes: ref(false)
|
||||
vi.mock('@/renderer/extensions/vueNodes/layout/useNodeDrag', () => {
|
||||
const startDrag = vi.fn()
|
||||
const handleDrag = vi.fn()
|
||||
const endDrag = vi.fn()
|
||||
return {
|
||||
useNodeDrag: () => ({
|
||||
startDrag,
|
||||
handleDrag,
|
||||
endDrag
|
||||
})
|
||||
}
|
||||
}))
|
||||
})
|
||||
|
||||
vi.mock('@/renderer/core/canvas/canvasStore', () => ({
|
||||
useCanvasStore: () => ({
|
||||
@@ -44,14 +43,23 @@ vi.mock('@/renderer/core/canvas/canvasStore', () => ({
|
||||
|
||||
vi.mock(
|
||||
'@/renderer/extensions/vueNodes/composables/useNodeEventHandlers',
|
||||
() => ({
|
||||
useNodeEventHandlers: () => ({
|
||||
deselectNode: deselectNodeMock,
|
||||
selectNodes: selectNodesMock,
|
||||
toggleNodeSelectionAfterPointerUp: toggleNodeSelectionAfterPointerUpMock,
|
||||
ensureNodeSelectedForShiftDrag: ensureNodeSelectedForShiftDragMock
|
||||
})
|
||||
})
|
||||
() => {
|
||||
const handleNodeSelect = vi.fn()
|
||||
const deselectNode = vi.fn()
|
||||
const selectNodes = vi.fn()
|
||||
const toggleNodeSelectionAfterPointerUp = vi.fn()
|
||||
const ensureNodeSelectedForShiftDrag = vi.fn()
|
||||
|
||||
return {
|
||||
useNodeEventHandlers: () => ({
|
||||
handleNodeSelect,
|
||||
deselectNode,
|
||||
selectNodes,
|
||||
toggleNodeSelectionAfterPointerUp,
|
||||
ensureNodeSelectedForShiftDrag
|
||||
})
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
vi.mock('@/composables/graph/useVueNodeLifecycle', () => ({
|
||||
@@ -65,19 +73,35 @@ vi.mock('@/composables/graph/useVueNodeLifecycle', () => ({
|
||||
})
|
||||
}))
|
||||
|
||||
const createMockVueNodeData = (
|
||||
overrides: Partial<VueNodeData> = {}
|
||||
): VueNodeData => ({
|
||||
id: 'test-node-123',
|
||||
title: 'Test Node',
|
||||
type: 'TestNodeType',
|
||||
mode: 0,
|
||||
selected: false,
|
||||
executing: false,
|
||||
inputs: [],
|
||||
outputs: [],
|
||||
widgets: [],
|
||||
...overrides
|
||||
const mockData = vi.hoisted(() => {
|
||||
const fakeNodeLayout: NodeLayout = {
|
||||
id: '',
|
||||
position: { x: 0, y: 0 },
|
||||
size: { width: 100, height: 100 },
|
||||
zIndex: 1,
|
||||
visible: true,
|
||||
bounds: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 100,
|
||||
height: 100
|
||||
}
|
||||
}
|
||||
return { fakeNodeLayout }
|
||||
})
|
||||
|
||||
vi.mock('@/renderer/core/layout/store/layoutStore', () => {
|
||||
const isDraggingVueNodes = ref(false)
|
||||
const fakeNodeLayoutRef = ref(mockData.fakeNodeLayout)
|
||||
const getNodeLayoutRef = vi.fn(() => fakeNodeLayoutRef)
|
||||
const setSource = vi.fn()
|
||||
return {
|
||||
layoutStore: {
|
||||
isDraggingVueNodes,
|
||||
getNodeLayoutRef,
|
||||
setSource
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const createPointerEvent = (
|
||||
@@ -107,46 +131,34 @@ const createMouseEvent = (
|
||||
|
||||
describe('useNodePointerInteractions', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
vi.restoreAllMocks()
|
||||
selectedItemsState.items = []
|
||||
setActivePinia(createPinia())
|
||||
// Reset layout store state between tests
|
||||
const { layoutStore } = await import(
|
||||
'@/renderer/core/layout/store/layoutStore'
|
||||
)
|
||||
layoutStore.isDraggingVueNodes.value = false
|
||||
setActivePinia(createTestingPinia())
|
||||
})
|
||||
|
||||
it('should only start drag on left-click', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
const { handleNodeSelect } = useNodeEventHandlers()
|
||||
const { startDrag } = useNodeDrag()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions('test-node-123')
|
||||
|
||||
// Right-click should not trigger selection
|
||||
const rightClickEvent = createPointerEvent('pointerdown', { button: 2 })
|
||||
pointerHandlers.onPointerdown(rightClickEvent)
|
||||
|
||||
expect(mockOnNodeSelect).not.toHaveBeenCalled()
|
||||
expect(handleNodeSelect).not.toHaveBeenCalled()
|
||||
|
||||
// Left-click should trigger selection on pointer down
|
||||
const leftClickEvent = createPointerEvent('pointerdown', { button: 0 })
|
||||
pointerHandlers.onPointerdown(leftClickEvent)
|
||||
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledWith(leftClickEvent, mockNodeData)
|
||||
expect(startDrag).toHaveBeenCalledWith(leftClickEvent, 'test-node-123')
|
||||
})
|
||||
|
||||
it('should call onNodeSelect on pointer down', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
it.skip('should call onNodeSelect on pointer down', async () => {
|
||||
const { handleNodeSelect } = useNodeEventHandlers()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions('test-node-123')
|
||||
|
||||
// Selection should happen on pointer down
|
||||
const downEvent = createPointerEvent('pointerdown', {
|
||||
@@ -155,9 +167,9 @@ describe('useNodePointerInteractions', () => {
|
||||
})
|
||||
pointerHandlers.onPointerdown(downEvent)
|
||||
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledWith(downEvent, mockNodeData)
|
||||
expect(handleNodeSelect).toHaveBeenCalledWith(downEvent, 'test-node-123')
|
||||
|
||||
mockOnNodeSelect.mockClear()
|
||||
vi.mocked(handleNodeSelect).mockClear()
|
||||
|
||||
// Even if we drag, selection already happened on pointer down
|
||||
pointerHandlers.onPointerup(
|
||||
@@ -165,35 +177,36 @@ describe('useNodePointerInteractions', () => {
|
||||
)
|
||||
|
||||
// onNodeSelect should not be called again on pointer up
|
||||
expect(mockOnNodeSelect).not.toHaveBeenCalled()
|
||||
expect(handleNodeSelect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should handle drag termination via cancel and context menu', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
const { handleNodeSelect } = useNodeEventHandlers()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions('test-node-123')
|
||||
|
||||
// Test pointer cancel - selection happens on pointer down
|
||||
pointerHandlers.onPointerdown(
|
||||
createPointerEvent('pointerdown', { clientX: 100, clientY: 100 })
|
||||
)
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledTimes(1)
|
||||
|
||||
// Simulate drag by moving pointer beyond threshold
|
||||
pointerHandlers.onPointermove(
|
||||
createPointerEvent('pointermove', { clientX: 110, clientY: 110 })
|
||||
createPointerEvent('pointermove', {
|
||||
clientX: 110,
|
||||
clientY: 110,
|
||||
buttons: 1
|
||||
})
|
||||
)
|
||||
|
||||
expect(handleNodeSelect).toHaveBeenCalledTimes(1)
|
||||
|
||||
pointerHandlers.onPointercancel(createPointerEvent('pointercancel'))
|
||||
|
||||
// Selection should have been called on pointer down only
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledTimes(1)
|
||||
expect(handleNodeSelect).toHaveBeenCalledTimes(1)
|
||||
|
||||
mockOnNodeSelect.mockClear()
|
||||
vi.mocked(handleNodeSelect).mockClear()
|
||||
|
||||
// Test context menu during drag prevents default
|
||||
pointerHandlers.onPointerdown(
|
||||
@@ -201,7 +214,11 @@ describe('useNodePointerInteractions', () => {
|
||||
)
|
||||
// Simulate drag by moving pointer beyond threshold
|
||||
pointerHandlers.onPointermove(
|
||||
createPointerEvent('pointermove', { clientX: 110, clientY: 110 })
|
||||
createPointerEvent('pointermove', {
|
||||
clientX: 110,
|
||||
clientY: 110,
|
||||
buttons: 1
|
||||
})
|
||||
)
|
||||
|
||||
const contextMenuEvent = createMouseEvent('contextmenu')
|
||||
@@ -212,36 +229,8 @@ describe('useNodePointerInteractions', () => {
|
||||
expect(preventDefaultSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not call onNodeSelect when nodeData is null', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
const nodeDataRef = ref<VueNodeData | null>(mockNodeData)
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
nodeDataRef,
|
||||
mockOnNodeSelect
|
||||
)
|
||||
|
||||
// Clear nodeData before pointer down
|
||||
nodeDataRef.value = null
|
||||
await nextTick()
|
||||
|
||||
pointerHandlers.onPointerdown(createPointerEvent('pointerdown'))
|
||||
|
||||
expect(mockOnNodeSelect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should integrate with layout store dragging state', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
const { layoutStore } = await import(
|
||||
'@/renderer/core/layout/store/layoutStore'
|
||||
)
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions('test-node-123')
|
||||
|
||||
// Pointer down alone shouldn't set dragging state
|
||||
pointerHandlers.onPointerdown(
|
||||
@@ -251,7 +240,11 @@ describe('useNodePointerInteractions', () => {
|
||||
|
||||
// Move pointer beyond threshold to start drag
|
||||
pointerHandlers.onPointermove(
|
||||
createPointerEvent('pointermove', { clientX: 110, clientY: 110 })
|
||||
createPointerEvent('pointermove', {
|
||||
clientX: 110,
|
||||
clientY: 110,
|
||||
buttons: 1
|
||||
})
|
||||
)
|
||||
await nextTick()
|
||||
expect(layoutStore.isDraggingVueNodes.value).toBe(true)
|
||||
@@ -262,63 +255,8 @@ describe('useNodePointerInteractions', () => {
|
||||
expect(layoutStore.isDraggingVueNodes.value).toBe(false)
|
||||
})
|
||||
|
||||
it('should select node on pointer down with ctrl key for multi-select', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
|
||||
// Pointer down with ctrl key should pass the event with ctrl key set
|
||||
const ctrlDownEvent = createPointerEvent('pointerdown', {
|
||||
ctrlKey: true,
|
||||
clientX: 100,
|
||||
clientY: 100
|
||||
})
|
||||
pointerHandlers.onPointerdown(ctrlDownEvent)
|
||||
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledWith(ctrlDownEvent, mockNodeData)
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should select pinned node on pointer down but not start drag', async () => {
|
||||
const mockNodeData = createMockVueNodeData({
|
||||
flags: { pinned: true }
|
||||
})
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
const { layoutStore } = await import(
|
||||
'@/renderer/core/layout/store/layoutStore'
|
||||
)
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
|
||||
// Pointer down on pinned node
|
||||
const downEvent = createPointerEvent('pointerdown')
|
||||
pointerHandlers.onPointerdown(downEvent)
|
||||
|
||||
// Should select the node
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledWith(downEvent, mockNodeData)
|
||||
|
||||
// But should not start dragging
|
||||
expect(layoutStore.isDraggingVueNodes.value).toBe(false)
|
||||
})
|
||||
|
||||
it('should select node immediately when drag starts', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
const { layoutStore } = await import(
|
||||
'@/renderer/core/layout/store/layoutStore'
|
||||
)
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions('test-node-123')
|
||||
|
||||
// Pointer down should select node immediately
|
||||
const downEvent = createPointerEvent('pointerdown', {
|
||||
@@ -326,24 +264,25 @@ describe('useNodePointerInteractions', () => {
|
||||
clientY: 100
|
||||
})
|
||||
pointerHandlers.onPointerdown(downEvent)
|
||||
|
||||
// Selection should happen on pointer down (before move)
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledWith(downEvent, mockNodeData)
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledTimes(1)
|
||||
const { handleNodeSelect } = useNodeEventHandlers()
|
||||
|
||||
// Dragging state should NOT be active yet
|
||||
expect(layoutStore.isDraggingVueNodes.value).toBe(false)
|
||||
|
||||
const pointerMove = createPointerEvent('pointermove', {
|
||||
clientX: 150,
|
||||
clientY: 150,
|
||||
buttons: 1
|
||||
})
|
||||
// Move the pointer beyond threshold (start dragging)
|
||||
pointerHandlers.onPointermove(
|
||||
createPointerEvent('pointermove', { clientX: 150, clientY: 150 })
|
||||
)
|
||||
pointerHandlers.onPointermove(pointerMove)
|
||||
|
||||
// Now dragging state should be active
|
||||
expect(layoutStore.isDraggingVueNodes.value).toBe(true)
|
||||
|
||||
// Selection should still only have been called once (on pointer down)
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledTimes(1)
|
||||
// Selection should happen on pointer down (before move)
|
||||
expect(handleNodeSelect).toHaveBeenCalledWith(pointerMove, 'test-node-123')
|
||||
expect(handleNodeSelect).toHaveBeenCalledTimes(1)
|
||||
|
||||
// End drag
|
||||
pointerHandlers.onPointerup(
|
||||
@@ -351,17 +290,12 @@ describe('useNodePointerInteractions', () => {
|
||||
)
|
||||
|
||||
// Selection should still only have been called once
|
||||
expect(mockOnNodeSelect).toHaveBeenCalledTimes(1)
|
||||
expect(handleNodeSelect).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('on ctrl+click: calls toggleNodeSelectionAfterPointerUp on pointer up (not pointer down)', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
const { pointerHandlers } = useNodePointerInteractions('test-node-123')
|
||||
const { toggleNodeSelectionAfterPointerUp } = useNodeEventHandlers()
|
||||
|
||||
// Pointer down with ctrl
|
||||
const downEvent = createPointerEvent('pointerdown', {
|
||||
@@ -372,7 +306,7 @@ describe('useNodePointerInteractions', () => {
|
||||
pointerHandlers.onPointerdown(downEvent)
|
||||
|
||||
// On pointer down: toggle handler should NOT be called yet
|
||||
expect(toggleNodeSelectionAfterPointerUpMock).not.toHaveBeenCalled()
|
||||
expect(toggleNodeSelectionAfterPointerUp).not.toHaveBeenCalled()
|
||||
|
||||
// Pointer up with ctrl (no drag - same position)
|
||||
const upEvent = createPointerEvent('pointerup', {
|
||||
@@ -383,116 +317,9 @@ describe('useNodePointerInteractions', () => {
|
||||
pointerHandlers.onPointerup(upEvent)
|
||||
|
||||
// On pointer up: toggle handler IS called with correct params
|
||||
expect(toggleNodeSelectionAfterPointerUpMock).toHaveBeenCalledWith(
|
||||
mockNodeData.id,
|
||||
{
|
||||
wasSelectedAtPointerDown: false,
|
||||
multiSelect: true
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('on ctrl+drag: does NOT call toggleNodeSelectionAfterPointerUp', async () => {
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
|
||||
// Pointer down with ctrl
|
||||
const downEvent = createPointerEvent('pointerdown', {
|
||||
ctrlKey: true,
|
||||
clientX: 100,
|
||||
clientY: 100
|
||||
})
|
||||
pointerHandlers.onPointerdown(downEvent)
|
||||
|
||||
// Move beyond drag threshold
|
||||
pointerHandlers.onPointermove(
|
||||
createPointerEvent('pointermove', {
|
||||
ctrlKey: true,
|
||||
clientX: 110,
|
||||
clientY: 110
|
||||
})
|
||||
)
|
||||
|
||||
// Pointer up after drag
|
||||
const upEvent = createPointerEvent('pointerup', {
|
||||
ctrlKey: true,
|
||||
clientX: 110,
|
||||
clientY: 110
|
||||
})
|
||||
pointerHandlers.onPointerup(upEvent)
|
||||
|
||||
// When dragging: toggle handler should NOT be called
|
||||
expect(toggleNodeSelectionAfterPointerUpMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('selects node when shift drag starts without multi selection', async () => {
|
||||
selectedItemsState.items = []
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
|
||||
const pointerDownEvent = createPointerEvent('pointerdown', {
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
shiftKey: true
|
||||
})
|
||||
|
||||
pointerHandlers.onPointerdown(pointerDownEvent)
|
||||
|
||||
const pointerMoveEvent = createPointerEvent('pointermove', {
|
||||
clientX: 10,
|
||||
clientY: 10,
|
||||
shiftKey: true
|
||||
})
|
||||
|
||||
pointerHandlers.onPointermove(pointerMoveEvent)
|
||||
|
||||
expect(ensureNodeSelectedForShiftDragMock).toHaveBeenCalledWith(
|
||||
pointerMoveEvent,
|
||||
mockNodeData,
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
it('still ensures selection when shift drag starts with existing multi select', async () => {
|
||||
selectedItemsState.items = [{ id: 'a' }, { id: 'b' }]
|
||||
const mockNodeData = createMockVueNodeData()
|
||||
const mockOnNodeSelect = vi.fn()
|
||||
|
||||
const { pointerHandlers } = useNodePointerInteractions(
|
||||
ref(mockNodeData),
|
||||
mockOnNodeSelect
|
||||
)
|
||||
|
||||
const pointerDownEvent = createPointerEvent('pointerdown', {
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
shiftKey: true
|
||||
})
|
||||
|
||||
pointerHandlers.onPointerdown(pointerDownEvent)
|
||||
|
||||
const pointerMoveEvent = createPointerEvent('pointermove', {
|
||||
clientX: 10,
|
||||
clientY: 10,
|
||||
shiftKey: true
|
||||
})
|
||||
|
||||
pointerHandlers.onPointermove(pointerMoveEvent)
|
||||
|
||||
expect(ensureNodeSelectedForShiftDragMock).toHaveBeenCalledWith(
|
||||
pointerMoveEvent,
|
||||
mockNodeData,
|
||||
false
|
||||
expect(toggleNodeSelectionAfterPointerUp).toHaveBeenCalledWith(
|
||||
'test-node-123',
|
||||
true
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,37 +1,22 @@
|
||||
import { computed, onUnmounted, ref, toValue } from 'vue'
|
||||
import { onScopeDispose, ref, toValue } from 'vue'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
|
||||
import { isMiddlePointerInput } from '@/base/pointerUtils'
|
||||
import type { VueNodeData } from '@/composables/graph/useGraphNodeManager'
|
||||
import { useVueNodeLifecycle } from '@/composables/graph/useVueNodeLifecycle'
|
||||
import { useCanvasInteractions } from '@/renderer/core/canvas/useCanvasInteractions'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import { useNodeLayout } from '@/renderer/extensions/vueNodes/layout/useNodeLayout'
|
||||
import { useNodeEventHandlers } from '@/renderer/extensions/vueNodes/composables/useNodeEventHandlers'
|
||||
import { isMultiSelectKey } from '@/renderer/extensions/vueNodes/utils/selectionUtils'
|
||||
import { useNodeDrag } from '@/renderer/extensions/vueNodes/layout/useNodeDrag'
|
||||
|
||||
export function useNodePointerInteractions(
|
||||
nodeDataMaybe: MaybeRefOrGetter<VueNodeData | null>,
|
||||
onNodeSelect: (event: PointerEvent, nodeData: VueNodeData) => void
|
||||
nodeIdRef: MaybeRefOrGetter<string>
|
||||
) {
|
||||
const nodeData = computed(() => {
|
||||
const value = toValue(nodeDataMaybe)
|
||||
if (!value) {
|
||||
console.warn(
|
||||
'useNodePointerInteractions: nodeDataMaybe resolved to null/undefined'
|
||||
)
|
||||
return null
|
||||
}
|
||||
return value
|
||||
})
|
||||
|
||||
// Avoid potential null access during component initialization
|
||||
const nodeIdComputed = computed(() => nodeData.value?.id ?? '')
|
||||
const { startDrag, endDrag, handleDrag } = useNodeLayout(nodeIdComputed)
|
||||
const { startDrag, endDrag, handleDrag } = useNodeDrag()
|
||||
// Use canvas interactions for proper wheel event handling and pointer event capture control
|
||||
const { forwardEventToCanvas, shouldHandleNodePointerEvents } =
|
||||
useCanvasInteractions()
|
||||
const { toggleNodeSelectionAfterPointerUp, ensureNodeSelectedForShiftDrag } =
|
||||
const { handleNodeSelect, toggleNodeSelectionAfterPointerUp } =
|
||||
useNodeEventHandlers()
|
||||
const { nodeManager } = useVueNodeLifecycle()
|
||||
|
||||
@@ -41,33 +26,15 @@ export function useNodePointerInteractions(
|
||||
return true
|
||||
}
|
||||
|
||||
// Drag state for styling
|
||||
const isDragging = ref(false)
|
||||
const isPointerDown = ref(false)
|
||||
const wasSelectedAtPointerDown = ref(false) // Track if node was selected when pointer down occurred
|
||||
const dragStyle = computed(() => {
|
||||
if (nodeData.value?.flags?.pinned) {
|
||||
return { cursor: 'default' }
|
||||
}
|
||||
return { cursor: isDragging.value ? 'grabbing' : 'grab' }
|
||||
})
|
||||
const startPosition = ref({ x: 0, y: 0 })
|
||||
|
||||
const DRAG_THRESHOLD = 3 // pixels
|
||||
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
if (!nodeData.value) {
|
||||
console.warn(
|
||||
'LGraphNode: nodeData is null/undefined in handlePointerDown'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
function onPointerdown(event: PointerEvent) {
|
||||
if (forwardMiddlePointerIfNeeded(event)) return
|
||||
|
||||
// Only start drag on left-click (button 0)
|
||||
if (event.button !== 0) {
|
||||
return
|
||||
}
|
||||
if (event.button !== 0) return
|
||||
|
||||
// Don't handle pointer events when canvas is in panning mode - forward to canvas instead
|
||||
if (!shouldHandleNodePointerEvents.value) {
|
||||
@@ -75,69 +42,67 @@ export function useNodePointerInteractions(
|
||||
return
|
||||
}
|
||||
|
||||
// Track if node was selected before this pointer down
|
||||
// IMPORTANT: Read from actual LGraphNode, not nodeData, to get correct state
|
||||
const lgNode = nodeManager.value?.getNode(nodeData.value.id)
|
||||
wasSelectedAtPointerDown.value = lgNode?.selected ?? false
|
||||
|
||||
onNodeSelect(event, nodeData.value)
|
||||
|
||||
if (nodeData.value.flags?.pinned) {
|
||||
const nodeId = toValue(nodeIdRef)
|
||||
if (!nodeId) {
|
||||
console.warn(
|
||||
'LGraphNode: nodeData is null/undefined in handlePointerDown'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Record position for drag threshold calculation
|
||||
startPosition.value = { x: event.clientX, y: event.clientY }
|
||||
isPointerDown.value = true
|
||||
// IMPORTANT: Read from actual LGraphNode to get correct state
|
||||
if (nodeManager.value?.getNode(nodeId)?.flags?.pinned) {
|
||||
return
|
||||
}
|
||||
|
||||
// Don't start drag yet - wait for pointer move to exceed threshold
|
||||
startDrag(event)
|
||||
startPosition.value = { x: event.clientX, y: event.clientY }
|
||||
|
||||
startDrag(event, nodeId)
|
||||
}
|
||||
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
function onPointermove(event: PointerEvent) {
|
||||
if (forwardMiddlePointerIfNeeded(event)) return
|
||||
|
||||
const nodeId = toValue(nodeIdRef)
|
||||
|
||||
if (nodeManager.value?.getNode(nodeId)?.flags?.pinned) {
|
||||
return
|
||||
}
|
||||
|
||||
const multiSelect = isMultiSelectKey(event)
|
||||
|
||||
const lmbDown = event.buttons & 1
|
||||
if (lmbDown && multiSelect && !layoutStore.isDraggingVueNodes.value) {
|
||||
layoutStore.isDraggingVueNodes.value = true
|
||||
handleNodeSelect(event, nodeId)
|
||||
startDrag(event, nodeId)
|
||||
return
|
||||
}
|
||||
// Check if we should start dragging (pointer moved beyond threshold)
|
||||
if (isPointerDown.value && !isDragging.value) {
|
||||
if (lmbDown && !layoutStore.isDraggingVueNodes.value) {
|
||||
const dx = event.clientX - startPosition.value.x
|
||||
const dy = event.clientY - startPosition.value.y
|
||||
const distance = Math.sqrt(dx * dx + dy * dy)
|
||||
|
||||
if (distance > DRAG_THRESHOLD && nodeData.value) {
|
||||
// Start drag
|
||||
isDragging.value = true
|
||||
if (distance > DRAG_THRESHOLD) {
|
||||
layoutStore.isDraggingVueNodes.value = true
|
||||
ensureNodeSelectedForShiftDrag(
|
||||
event,
|
||||
nodeData.value,
|
||||
wasSelectedAtPointerDown.value
|
||||
)
|
||||
handleNodeSelect(event, nodeId)
|
||||
}
|
||||
}
|
||||
|
||||
if (isDragging.value) {
|
||||
void handleDrag(event)
|
||||
if (layoutStore.isDraggingVueNodes.value) {
|
||||
handleDrag(event, nodeId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Centralized cleanup function for drag state
|
||||
* Ensures consistent cleanup across all drag termination scenarios
|
||||
*/
|
||||
const cleanupDragState = () => {
|
||||
isDragging.value = false
|
||||
isPointerDown.value = false
|
||||
wasSelectedAtPointerDown.value = false
|
||||
function cleanupDragState() {
|
||||
layoutStore.isDraggingVueNodes.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely ends drag operation with proper error handling
|
||||
* @param event - PointerEvent to end the drag with
|
||||
*/
|
||||
const safeDragEnd = async (event: PointerEvent): Promise<void> => {
|
||||
function safeDragEnd(event: PointerEvent) {
|
||||
try {
|
||||
await endDrag(event)
|
||||
const nodeId = toValue(nodeIdRef)
|
||||
endDrag(event, nodeId)
|
||||
} catch (error) {
|
||||
console.error('Error during endDrag:', error)
|
||||
} finally {
|
||||
@@ -145,61 +110,39 @@ export function useNodePointerInteractions(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Common drag termination handler with fallback cleanup
|
||||
*/
|
||||
const handleDragTermination = (event: PointerEvent, errorContext: string) => {
|
||||
safeDragEnd(event).catch((error) => {
|
||||
console.error(`Failed to complete ${errorContext}:`, error)
|
||||
cleanupDragState() // Fallback cleanup
|
||||
})
|
||||
}
|
||||
|
||||
const handlePointerUp = (event: PointerEvent) => {
|
||||
function onPointerup(event: PointerEvent) {
|
||||
if (forwardMiddlePointerIfNeeded(event)) return
|
||||
|
||||
const wasDragging = isDragging.value
|
||||
const multiSelect = isMultiSelectKey(event)
|
||||
const canHandlePointer = shouldHandleNodePointerEvents.value
|
||||
|
||||
if (wasDragging) {
|
||||
handleDragTermination(event, 'drag end')
|
||||
} else {
|
||||
// Clean up pointer state even if not dragging
|
||||
isPointerDown.value = false
|
||||
const wasSelected = wasSelectedAtPointerDown.value
|
||||
wasSelectedAtPointerDown.value = false
|
||||
|
||||
if (nodeData.value && canHandlePointer) {
|
||||
toggleNodeSelectionAfterPointerUp(nodeData.value.id, {
|
||||
wasSelectedAtPointerDown: wasSelected,
|
||||
multiSelect
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Don't handle pointer events when canvas is in panning mode - forward to canvas instead
|
||||
const canHandlePointer = shouldHandleNodePointerEvents.value
|
||||
if (!canHandlePointer) {
|
||||
forwardEventToCanvas(event)
|
||||
return
|
||||
}
|
||||
const wasDragging = layoutStore.isDraggingVueNodes.value
|
||||
|
||||
if (wasDragging) {
|
||||
safeDragEnd(event)
|
||||
return
|
||||
}
|
||||
const multiSelect = isMultiSelectKey(event)
|
||||
|
||||
const nodeId = toValue(nodeIdRef)
|
||||
if (nodeId) {
|
||||
toggleNodeSelectionAfterPointerUp(nodeId, multiSelect)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles pointer cancellation events (e.g., touch cancelled by browser)
|
||||
* Ensures drag state is properly cleaned up when pointer interaction is interrupted
|
||||
*/
|
||||
const handlePointerCancel = (event: PointerEvent) => {
|
||||
if (!isDragging.value) return
|
||||
handleDragTermination(event, 'drag cancellation')
|
||||
function onPointercancel(event: PointerEvent) {
|
||||
if (!layoutStore.isDraggingVueNodes.value) return
|
||||
safeDragEnd(event)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles right-click during drag operations
|
||||
* Cancels the current drag to prevent context menu from appearing while dragging
|
||||
*/
|
||||
const handleContextMenu = (event: MouseEvent) => {
|
||||
if (!isDragging.value) return
|
||||
function onContextmenu(event: MouseEvent) {
|
||||
if (!layoutStore.isDraggingVueNodes.value) return
|
||||
|
||||
event.preventDefault()
|
||||
// Simply cleanup state without calling endDrag to avoid synthetic event creation
|
||||
@@ -207,22 +150,19 @@ export function useNodePointerInteractions(
|
||||
}
|
||||
|
||||
// Cleanup on unmount to prevent resource leaks
|
||||
onUnmounted(() => {
|
||||
if (!isDragging.value) return
|
||||
onScopeDispose(() => {
|
||||
cleanupDragState()
|
||||
})
|
||||
|
||||
const pointerHandlers = {
|
||||
onPointerdown: handlePointerDown,
|
||||
onPointermove: handlePointerMove,
|
||||
onPointerup: handlePointerUp,
|
||||
onPointercancel: handlePointerCancel,
|
||||
onContextmenu: handleContextMenu
|
||||
}
|
||||
onPointerdown,
|
||||
onPointermove,
|
||||
onPointerup,
|
||||
onPointercancel,
|
||||
onContextmenu
|
||||
} as const
|
||||
|
||||
return {
|
||||
isDragging,
|
||||
dragStyle,
|
||||
pointerHandlers
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,6 +384,8 @@ export function useSlotLinkInteraction({
|
||||
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
if (!pointerSession.matches(event)) return
|
||||
event.stopPropagation()
|
||||
|
||||
dragContext.pendingPointerMove = {
|
||||
clientX: event.clientX,
|
||||
clientY: event.clientY,
|
||||
@@ -507,6 +509,7 @@ export function useSlotLinkInteraction({
|
||||
}
|
||||
|
||||
const handlePointerUp = (event: PointerEvent) => {
|
||||
event.stopPropagation()
|
||||
finishInteraction(event)
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { MaybeRefOrGetter } from 'vue'
|
||||
import { useSharedCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion'
|
||||
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import type { Bounds, NodeId } from '@/renderer/core/layout/types'
|
||||
import { LayoutSource } from '@/renderer/core/layout/types'
|
||||
|
||||
@@ -60,6 +61,7 @@ const trackingConfigs: Map<string, ElementTrackingConfig> = new Map([
|
||||
|
||||
// Single ResizeObserver instance for all Vue elements
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
if (useCanvasStore().linearMode) return
|
||||
// Canvas is ready when this code runs; no defensive guards needed.
|
||||
const conv = useSharedCanvasPositionConversion()
|
||||
// Group updates by type, then flush via each config's handler
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
import { useEventListener } from '@vueuse/core'
|
||||
import { ref } from 'vue'
|
||||
|
||||
import type { TransformState } from '@/renderer/core/layout/injectionKeys'
|
||||
import type { Point, Size } from '@/renderer/core/layout/types'
|
||||
import { useNodeSnap } from '@/renderer/extensions/vueNodes/composables/useNodeSnap'
|
||||
import { useShiftKeySync } from '@/renderer/extensions/vueNodes/composables/useShiftKeySync'
|
||||
|
||||
import type { ResizeHandleDirection } from './resizeMath'
|
||||
import { createResizeSession, toCanvasDelta } from './resizeMath'
|
||||
|
||||
interface UseNodeResizeOptions {
|
||||
/** Transform state for coordinate conversion */
|
||||
transformState: TransformState
|
||||
}
|
||||
import { useTransformState } from '@/renderer/core/layout/transform/useTransformState'
|
||||
|
||||
interface ResizeCallbackPayload {
|
||||
size: Size
|
||||
@@ -26,13 +21,9 @@ interface ResizeCallbackPayload {
|
||||
* Handles pointer capture, coordinate calculations, and size constraints.
|
||||
*/
|
||||
export function useNodeResize(
|
||||
resizeCallback: (
|
||||
payload: ResizeCallbackPayload,
|
||||
element: HTMLElement
|
||||
) => void,
|
||||
options: UseNodeResizeOptions
|
||||
resizeCallback: (payload: ResizeCallbackPayload, element: HTMLElement) => void
|
||||
) {
|
||||
const { transformState } = options
|
||||
const transformState = useTransformState()
|
||||
|
||||
const isResizing = ref(false)
|
||||
const resizeStartPointer = ref<Point | null>(null)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useVueFeatureFlags } from '@/composables/useVueFeatureFlags'
|
||||
import type { LGraph, rendererType } from '@/lib/litegraph/src/LGraph'
|
||||
import type { LGraph, RendererType } from '@/lib/litegraph/src/LGraph'
|
||||
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { createBounds } from '@/lib/litegraph/src/measure'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
@@ -13,135 +13,108 @@ import type { SubgraphOutputNode } from '@/lib/litegraph/src/subgraph/SubgraphOu
|
||||
const SCALE_FACTOR = 1.2
|
||||
|
||||
export function ensureCorrectLayoutScale(
|
||||
renderer?: rendererType,
|
||||
renderer: RendererType = 'LG',
|
||||
targetGraph?: LGraph
|
||||
) {
|
||||
const settingStore = useSettingStore()
|
||||
|
||||
const autoScaleLayoutSetting = settingStore.get(
|
||||
const autoScaleLayoutSetting = useSettingStore().get(
|
||||
'Comfy.VueNodes.AutoScaleLayout'
|
||||
)
|
||||
|
||||
if (autoScaleLayoutSetting === false) {
|
||||
return
|
||||
}
|
||||
|
||||
const { shouldRenderVueNodes } = useVueFeatureFlags()
|
||||
if (!autoScaleLayoutSetting) return
|
||||
|
||||
const canvas = comfyApp.canvas
|
||||
const graph = targetGraph ?? canvas?.graph
|
||||
|
||||
if (!graph || !graph.nodes) return
|
||||
if (!graph?.nodes) return
|
||||
|
||||
// Use renderer from graph, default to 'LG' for the check (but don't modify graph yet)
|
||||
if (!renderer) {
|
||||
// Always assume legacy LG format when unknown (pre-dates this feature)
|
||||
renderer = 'LG'
|
||||
}
|
||||
const { shouldRenderVueNodes } = useVueFeatureFlags()
|
||||
|
||||
const doesntNeedScale =
|
||||
(renderer === 'LG' && shouldRenderVueNodes.value === false) ||
|
||||
(renderer === 'Vue' && shouldRenderVueNodes.value === true)
|
||||
const needsUpscale = renderer === 'LG' && shouldRenderVueNodes.value
|
||||
const needsDownscale = renderer === 'Vue' && !shouldRenderVueNodes.value
|
||||
|
||||
if (doesntNeedScale) {
|
||||
if (!needsUpscale && !needsDownscale) {
|
||||
// Don't scale, but ensure workflowRendererVersion is set for future checks
|
||||
if (!graph.extra.workflowRendererVersion) {
|
||||
graph.extra.workflowRendererVersion = renderer
|
||||
}
|
||||
graph.extra.workflowRendererVersion ??= renderer
|
||||
return
|
||||
}
|
||||
|
||||
const needsUpscale = renderer === 'LG' && shouldRenderVueNodes.value === true
|
||||
const needsDownscale =
|
||||
renderer === 'Vue' && shouldRenderVueNodes.value === false
|
||||
|
||||
const lgBounds = createBounds(graph.nodes)
|
||||
|
||||
if (!lgBounds) return
|
||||
|
||||
const originX = lgBounds[0]
|
||||
const originY = lgBounds[1]
|
||||
const [originX, originY] = lgBounds
|
||||
|
||||
const lgNodesById = new Map(graph.nodes.map((node) => [node.id, node]))
|
||||
|
||||
const yjsMoveNodeUpdates: NodeBoundsUpdate[] = []
|
||||
|
||||
const scaleFactor = needsUpscale
|
||||
? SCALE_FACTOR
|
||||
: needsDownscale
|
||||
? 1 / SCALE_FACTOR
|
||||
: 1
|
||||
const scaleFactor = needsUpscale ? SCALE_FACTOR : 1 / SCALE_FACTOR
|
||||
|
||||
const onActiveGraph = !targetGraph || targetGraph === canvas?.graph
|
||||
|
||||
//TODO: once we remove the need for LiteGraph.NODE_TITLE_HEIGHT in vue nodes we nned to remove everything here.
|
||||
for (const node of graph.nodes) {
|
||||
const lgNode = lgNodesById.get(node.id)
|
||||
if (!lgNode) continue
|
||||
|
||||
const lgBodyY = lgNode.pos[1]
|
||||
const [oldX, oldY] = lgNode.pos
|
||||
|
||||
const adjustedY = needsDownscale
|
||||
? lgBodyY - LiteGraph.NODE_TITLE_HEIGHT / 2
|
||||
: lgBodyY
|
||||
const adjustedY = oldY - (needsUpscale ? LiteGraph.NODE_TITLE_HEIGHT : 0)
|
||||
|
||||
const relativeX = lgNode.pos[0] - originX
|
||||
const relativeX = oldX - originX
|
||||
const relativeY = adjustedY - originY
|
||||
const newX = originX + relativeX * scaleFactor
|
||||
const scaledY = originY + relativeY * scaleFactor
|
||||
const newWidth = lgNode.width * scaleFactor
|
||||
const newHeight = lgNode.height * scaleFactor
|
||||
|
||||
const finalY = needsUpscale
|
||||
? scaledY + LiteGraph.NODE_TITLE_HEIGHT / 2
|
||||
: scaledY
|
||||
const scaledX = originX + relativeX * scaleFactor
|
||||
const scaledY = originY + relativeY * scaleFactor
|
||||
|
||||
const scaledWidth = lgNode.width * scaleFactor
|
||||
const scaledHeight =
|
||||
lgNode.height * scaleFactor -
|
||||
(needsUpscale ? 0 : LiteGraph.NODE_TITLE_HEIGHT)
|
||||
|
||||
const finalY = scaledY + (needsUpscale ? 0 : LiteGraph.NODE_TITLE_HEIGHT) // Litegraph Position further down
|
||||
|
||||
// Directly update LiteGraph node to ensure immediate consistency
|
||||
// Dont need to reference vue directly because the pos and dims are already in yjs
|
||||
lgNode.pos[0] = newX
|
||||
lgNode.pos[0] = scaledX
|
||||
lgNode.pos[1] = finalY
|
||||
lgNode.size[0] = newWidth
|
||||
lgNode.size[1] =
|
||||
newHeight - (needsDownscale ? LiteGraph.NODE_TITLE_HEIGHT : 0)
|
||||
lgNode.size[0] = scaledWidth
|
||||
lgNode.size[1] = scaledHeight
|
||||
|
||||
// Track updates for layout store (only if this is the active graph)
|
||||
if (!targetGraph || targetGraph === canvas?.graph) {
|
||||
if (onActiveGraph) {
|
||||
yjsMoveNodeUpdates.push({
|
||||
nodeId: String(lgNode.id),
|
||||
bounds: {
|
||||
x: newX,
|
||||
x: scaledX,
|
||||
y: finalY,
|
||||
width: newWidth,
|
||||
height: newHeight - (needsDownscale ? LiteGraph.NODE_TITLE_HEIGHT : 0)
|
||||
width: scaledWidth,
|
||||
height: scaledHeight
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
(!targetGraph || targetGraph === canvas?.graph) &&
|
||||
yjsMoveNodeUpdates.length > 0
|
||||
) {
|
||||
if (onActiveGraph && yjsMoveNodeUpdates.length > 0) {
|
||||
layoutStore.batchUpdateNodeBounds(yjsMoveNodeUpdates)
|
||||
}
|
||||
|
||||
for (const reroute of graph.reroutes.values()) {
|
||||
const oldX = reroute.pos[0]
|
||||
const oldY = reroute.pos[1]
|
||||
const [oldX, oldY] = reroute.pos
|
||||
|
||||
const relativeX = oldX - originX
|
||||
const relativeY = oldY - originY
|
||||
const newX = originX + relativeX * scaleFactor
|
||||
const newY = originY + relativeY * scaleFactor
|
||||
|
||||
reroute.pos = [newX, newY]
|
||||
const scaledX = originX + relativeX * scaleFactor
|
||||
const scaledY = originY + relativeY * scaleFactor
|
||||
|
||||
if (
|
||||
(!targetGraph || targetGraph === canvas?.graph) &&
|
||||
shouldRenderVueNodes.value
|
||||
) {
|
||||
reroute.pos = [scaledX, scaledY]
|
||||
|
||||
if (onActiveGraph && shouldRenderVueNodes.value) {
|
||||
const layoutMutations = useLayoutMutations()
|
||||
layoutMutations.moveReroute(
|
||||
reroute.id,
|
||||
{ x: newX, y: newY },
|
||||
{ x: scaledX, y: scaledY },
|
||||
{ x: oldX, y: oldY }
|
||||
)
|
||||
}
|
||||
@@ -153,60 +126,48 @@ export function ensureCorrectLayoutScale(
|
||||
graph.outputNode as SubgraphOutputNode
|
||||
]
|
||||
for (const ioNode of ioNodes) {
|
||||
const oldX = ioNode.pos[0]
|
||||
const oldY = ioNode.pos[1]
|
||||
const oldWidth = ioNode.size[0]
|
||||
const oldHeight = ioNode.size[1]
|
||||
const [oldX, oldY] = ioNode.pos
|
||||
const [oldWidth, oldHeight] = ioNode.size
|
||||
|
||||
const relativeX = oldX - originX
|
||||
const relativeY = oldY - originY
|
||||
const newX = originX + relativeX * scaleFactor
|
||||
const newY = originY + relativeY * scaleFactor
|
||||
const newWidth = oldWidth * scaleFactor
|
||||
const newHeight = oldHeight * scaleFactor
|
||||
|
||||
ioNode.pos = [newX, newY]
|
||||
ioNode.size = [newWidth, newHeight]
|
||||
const scaledX = originX + relativeX * scaleFactor
|
||||
const scaledY = originY + relativeY * scaleFactor
|
||||
|
||||
const scaledWidth = oldWidth * scaleFactor
|
||||
const scaledHeight = oldHeight * scaleFactor
|
||||
|
||||
ioNode.pos = [scaledX, scaledY]
|
||||
ioNode.size = [scaledWidth, scaledHeight]
|
||||
}
|
||||
}
|
||||
|
||||
graph.groups.forEach((group) => {
|
||||
const originalPosX = group.pos[0]
|
||||
const originalPosY = group.pos[1]
|
||||
const originalWidth = group.size[0]
|
||||
const originalHeight = group.size[1]
|
||||
const [oldX, oldY] = group.pos
|
||||
const [oldWidth, oldHeight] = group.size
|
||||
|
||||
const adjustedY = needsDownscale
|
||||
? originalPosY - LiteGraph.NODE_TITLE_HEIGHT
|
||||
: originalPosY
|
||||
const adjustedY = oldY - (needsUpscale ? LiteGraph.NODE_TITLE_HEIGHT : 0)
|
||||
|
||||
const relativeX = originalPosX - originX
|
||||
const relativeX = oldX - originX
|
||||
const relativeY = adjustedY - originY
|
||||
|
||||
const newWidth = originalWidth * scaleFactor
|
||||
const newHeight = originalHeight * scaleFactor
|
||||
|
||||
const scaledX = originX + relativeX * scaleFactor
|
||||
const scaledY = originY + relativeY * scaleFactor
|
||||
|
||||
const finalY = needsUpscale
|
||||
? scaledY + LiteGraph.NODE_TITLE_HEIGHT
|
||||
: scaledY
|
||||
const scaledWidth = oldWidth * scaleFactor
|
||||
const scaledHeight = oldHeight * scaleFactor
|
||||
|
||||
const finalY = scaledY + (needsUpscale ? 0 : LiteGraph.NODE_TITLE_HEIGHT)
|
||||
|
||||
group.pos = [scaledX, finalY]
|
||||
group.size = [newWidth, newHeight]
|
||||
group.size = [scaledWidth, scaledHeight]
|
||||
})
|
||||
|
||||
if ((!targetGraph || targetGraph === canvas?.graph) && canvas) {
|
||||
if (onActiveGraph && canvas) {
|
||||
const originScreen = canvas.ds.convertOffsetToCanvas([originX, originY])
|
||||
canvas.ds.changeScale(canvas.ds.scale / scaleFactor, originScreen)
|
||||
}
|
||||
|
||||
if (needsUpscale) {
|
||||
graph.extra.workflowRendererVersion = 'Vue'
|
||||
}
|
||||
|
||||
if (needsDownscale) {
|
||||
graph.extra.workflowRendererVersion = 'LG'
|
||||
}
|
||||
graph.extra.workflowRendererVersion = needsUpscale ? 'Vue' : 'LG'
|
||||
}
|
||||
|
||||
215
src/renderer/extensions/vueNodes/layout/useNodeDrag.ts
Normal file
215
src/renderer/extensions/vueNodes/layout/useNodeDrag.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { toValue } from 'vue'
|
||||
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import { LayoutSource } from '@/renderer/core/layout/types'
|
||||
import type {
|
||||
NodeBoundsUpdate,
|
||||
NodeId,
|
||||
Point
|
||||
} from '@/renderer/core/layout/types'
|
||||
import { useNodeSnap } from '@/renderer/extensions/vueNodes/composables/useNodeSnap'
|
||||
import { useShiftKeySync } from '@/renderer/extensions/vueNodes/composables/useShiftKeySync'
|
||||
import { useTransformState } from '@/renderer/core/layout/transform/useTransformState'
|
||||
import { createSharedComposable } from '@vueuse/core'
|
||||
|
||||
export const useNodeDrag = createSharedComposable(useNodeDragIndividual)
|
||||
|
||||
function useNodeDragIndividual() {
|
||||
const mutations = useLayoutMutations()
|
||||
const { selectedNodeIds } = storeToRefs(useCanvasStore())
|
||||
|
||||
// Get transform utilities from TransformPane if available
|
||||
const transformState = useTransformState()
|
||||
|
||||
// Snap-to-grid functionality
|
||||
const { shouldSnap, applySnapToPosition } = useNodeSnap()
|
||||
|
||||
// Shift key sync for LiteGraph canvas preview
|
||||
const { trackShiftKey } = useShiftKeySync()
|
||||
|
||||
// Drag state
|
||||
let dragStartPos: Point | null = null
|
||||
let dragStartMouse: Point | null = null
|
||||
let otherSelectedNodesStartPositions: Map<string, Point> | null = null
|
||||
let rafId: number | null = null
|
||||
let stopShiftSync: (() => void) | null = null
|
||||
|
||||
function startDrag(event: PointerEvent, nodeId: NodeId) {
|
||||
const layout = toValue(layoutStore.getNodeLayoutRef(nodeId))
|
||||
if (!layout) return
|
||||
const position = layout.position ?? { x: 0, y: 0 }
|
||||
|
||||
// Track shift key state and sync to canvas for snap preview
|
||||
stopShiftSync = trackShiftKey(event)
|
||||
|
||||
dragStartPos = { ...position }
|
||||
dragStartMouse = { x: event.clientX, y: event.clientY }
|
||||
|
||||
const selectedNodes = toValue(selectedNodeIds)
|
||||
|
||||
// capture the starting positions of all other selected nodes
|
||||
if (selectedNodes?.has(nodeId) && selectedNodes.size > 1) {
|
||||
otherSelectedNodesStartPositions = new Map()
|
||||
|
||||
for (const id of selectedNodes) {
|
||||
// Skip the current node being dragged
|
||||
if (id === nodeId) continue
|
||||
|
||||
const nodeLayout = layoutStore.getNodeLayoutRef(id).value
|
||||
if (nodeLayout) {
|
||||
otherSelectedNodesStartPositions.set(id, { ...nodeLayout.position })
|
||||
}
|
||||
}
|
||||
} else {
|
||||
otherSelectedNodesStartPositions = null
|
||||
}
|
||||
|
||||
mutations.setSource(LayoutSource.Vue)
|
||||
}
|
||||
|
||||
function handleDrag(event: PointerEvent, nodeId: NodeId) {
|
||||
if (!dragStartPos || !dragStartMouse) {
|
||||
return
|
||||
}
|
||||
|
||||
// Throttle position updates using requestAnimationFrame for better performance
|
||||
if (rafId !== null) return // Skip if frame already scheduled
|
||||
|
||||
const { target, pointerId } = event
|
||||
if (target instanceof HTMLElement && !target.hasPointerCapture(pointerId)) {
|
||||
// Delay capture to drag to allow for the Node cloning
|
||||
target.setPointerCapture(pointerId)
|
||||
}
|
||||
rafId = requestAnimationFrame(() => {
|
||||
rafId = null
|
||||
|
||||
if (!dragStartPos || !dragStartMouse) return
|
||||
|
||||
// Calculate mouse delta in screen coordinates
|
||||
const mouseDelta = {
|
||||
x: event.clientX - dragStartMouse.x,
|
||||
y: event.clientY - dragStartMouse.y
|
||||
}
|
||||
|
||||
// Convert to canvas coordinates
|
||||
const canvasOrigin = transformState.screenToCanvas({ x: 0, y: 0 })
|
||||
const canvasWithDelta = transformState.screenToCanvas(mouseDelta)
|
||||
const canvasDelta = {
|
||||
x: canvasWithDelta.x - canvasOrigin.x,
|
||||
y: canvasWithDelta.y - canvasOrigin.y
|
||||
}
|
||||
|
||||
// Calculate new position for the current node
|
||||
const newPosition = {
|
||||
x: dragStartPos.x + canvasDelta.x,
|
||||
y: dragStartPos.y + canvasDelta.y
|
||||
}
|
||||
|
||||
// Apply mutation through the layout system (Vue batches DOM updates automatically)
|
||||
mutations.moveNode(nodeId, newPosition)
|
||||
|
||||
// If we're dragging multiple selected nodes, move them all together
|
||||
if (
|
||||
otherSelectedNodesStartPositions &&
|
||||
otherSelectedNodesStartPositions.size > 0
|
||||
) {
|
||||
for (const [
|
||||
otherNodeId,
|
||||
startPos
|
||||
] of otherSelectedNodesStartPositions) {
|
||||
const newOtherPosition = {
|
||||
x: startPos.x + canvasDelta.x,
|
||||
y: startPos.y + canvasDelta.y
|
||||
}
|
||||
mutations.moveNode(otherNodeId, newOtherPosition)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function endDrag(event: PointerEvent, nodeId: NodeId | undefined) {
|
||||
// Apply snap to final position if snap was active (matches LiteGraph behavior)
|
||||
if (shouldSnap(event) && nodeId) {
|
||||
const boundsUpdates: NodeBoundsUpdate[] = []
|
||||
|
||||
// Snap main node
|
||||
const currentLayout = toValue(layoutStore.getNodeLayoutRef(nodeId))
|
||||
if (currentLayout) {
|
||||
const currentPos = currentLayout.position
|
||||
const snappedPos = applySnapToPosition({ ...currentPos })
|
||||
|
||||
// Only add update if position actually changed
|
||||
if (snappedPos.x !== currentPos.x || snappedPos.y !== currentPos.y) {
|
||||
boundsUpdates.push({
|
||||
nodeId,
|
||||
bounds: {
|
||||
x: snappedPos.x,
|
||||
y: snappedPos.y,
|
||||
width: currentLayout.size.width,
|
||||
height: currentLayout.size.height
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Also snap other selected nodes
|
||||
// Capture all positions at the start to ensure consistent state
|
||||
if (
|
||||
otherSelectedNodesStartPositions &&
|
||||
otherSelectedNodesStartPositions.size > 0
|
||||
) {
|
||||
for (const otherNodeId of otherSelectedNodesStartPositions.keys()) {
|
||||
const nodeLayout = layoutStore.getNodeLayoutRef(otherNodeId).value
|
||||
if (nodeLayout) {
|
||||
const currentPos = { ...nodeLayout.position }
|
||||
const snappedPos = applySnapToPosition(currentPos)
|
||||
|
||||
// Only add update if position actually changed
|
||||
if (
|
||||
snappedPos.x !== currentPos.x ||
|
||||
snappedPos.y !== currentPos.y
|
||||
) {
|
||||
boundsUpdates.push({
|
||||
nodeId: otherNodeId,
|
||||
bounds: {
|
||||
x: snappedPos.x,
|
||||
y: snappedPos.y,
|
||||
width: nodeLayout.size.width,
|
||||
height: nodeLayout.size.height
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply all snap updates in a single batched transaction
|
||||
if (boundsUpdates.length > 0) {
|
||||
layoutStore.batchUpdateNodeBounds(boundsUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
dragStartPos = null
|
||||
dragStartMouse = null
|
||||
otherSelectedNodesStartPositions = null
|
||||
|
||||
// Stop tracking shift key state
|
||||
stopShiftSync?.()
|
||||
stopShiftSync = null
|
||||
|
||||
// Cancel any pending animation frame
|
||||
if (rafId !== null) {
|
||||
cancelAnimationFrame(rafId)
|
||||
rafId = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
startDrag,
|
||||
handleDrag,
|
||||
endDrag
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, inject, ref, toValue } from 'vue'
|
||||
import type { CSSProperties, MaybeRefOrGetter } from 'vue'
|
||||
import { computed, toValue } from 'vue'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import { TransformStateKey } from '@/renderer/core/layout/injectionKeys'
|
||||
import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import { LayoutSource } from '@/renderer/core/layout/types'
|
||||
import type { NodeBoundsUpdate, Point } from '@/renderer/core/layout/types'
|
||||
import { useNodeSnap } from '@/renderer/extensions/vueNodes/composables/useNodeSnap'
|
||||
import { useShiftKeySync } from '@/renderer/extensions/vueNodes/composables/useShiftKeySync'
|
||||
import type { Point } from '@/renderer/core/layout/types'
|
||||
|
||||
/**
|
||||
* Composable for individual Vue node components
|
||||
@@ -18,16 +13,6 @@ import { useShiftKeySync } from '@/renderer/extensions/vueNodes/composables/useS
|
||||
export function useNodeLayout(nodeIdMaybe: MaybeRefOrGetter<string>) {
|
||||
const nodeId = toValue(nodeIdMaybe)
|
||||
const mutations = useLayoutMutations()
|
||||
const { selectedNodeIds } = storeToRefs(useCanvasStore())
|
||||
|
||||
// Get transform utilities from TransformPane if available
|
||||
const transformState = inject(TransformStateKey)
|
||||
|
||||
// Snap-to-grid functionality
|
||||
const { shouldSnap, applySnapToPosition } = useNodeSnap()
|
||||
|
||||
// Shift key sync for LiteGraph canvas preview
|
||||
const { trackShiftKey } = useShiftKeySync()
|
||||
|
||||
// Get the customRef for this node (shared write access)
|
||||
const layoutRef = layoutStore.getNodeLayoutRef(nodeId)
|
||||
@@ -41,215 +26,9 @@ export function useNodeLayout(nodeIdMaybe: MaybeRefOrGetter<string>) {
|
||||
const size = computed(
|
||||
() => layoutRef.value?.size ?? { width: 200, height: 100 }
|
||||
)
|
||||
const bounds = computed(
|
||||
() =>
|
||||
layoutRef.value?.bounds ?? {
|
||||
x: position.value.x,
|
||||
y: position.value.y,
|
||||
width: size.value.width,
|
||||
height: size.value.height
|
||||
}
|
||||
)
|
||||
const isVisible = computed(() => layoutRef.value?.visible ?? true)
|
||||
|
||||
const zIndex = computed(() => layoutRef.value?.zIndex ?? 0)
|
||||
|
||||
// Drag state
|
||||
const isDragging = ref(false)
|
||||
let dragStartPos: Point | null = null
|
||||
let dragStartMouse: Point | null = null
|
||||
let otherSelectedNodesStartPositions: Map<string, Point> | null = null
|
||||
let rafId: number | null = null
|
||||
let stopShiftSync: (() => void) | null = null
|
||||
|
||||
/**
|
||||
* Start dragging the node
|
||||
*/
|
||||
function startDrag(event: PointerEvent) {
|
||||
if (!layoutRef.value || !transformState) return
|
||||
|
||||
// Track shift key state and sync to canvas for snap preview
|
||||
stopShiftSync = trackShiftKey(event)
|
||||
|
||||
isDragging.value = true
|
||||
dragStartPos = { ...position.value }
|
||||
dragStartMouse = { x: event.clientX, y: event.clientY }
|
||||
|
||||
// capture the starting positions of all other selected nodes
|
||||
if (selectedNodeIds?.value?.has(nodeId) && selectedNodeIds.value.size > 1) {
|
||||
otherSelectedNodesStartPositions = new Map()
|
||||
|
||||
// Iterate through all selected node IDs
|
||||
for (const id of selectedNodeIds.value) {
|
||||
// Skip the current node being dragged
|
||||
if (id === nodeId) continue
|
||||
|
||||
const nodeLayout = layoutStore.getNodeLayoutRef(id).value
|
||||
if (nodeLayout) {
|
||||
otherSelectedNodesStartPositions.set(id, { ...nodeLayout.position })
|
||||
}
|
||||
}
|
||||
} else {
|
||||
otherSelectedNodesStartPositions = null
|
||||
}
|
||||
|
||||
// Set mutation source
|
||||
mutations.setSource(LayoutSource.Vue)
|
||||
|
||||
// Capture pointer
|
||||
if (!(event.target instanceof HTMLElement)) return
|
||||
event.target.setPointerCapture(event.pointerId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle drag movement
|
||||
*/
|
||||
const handleDrag = (event: PointerEvent) => {
|
||||
if (
|
||||
!isDragging.value ||
|
||||
!dragStartPos ||
|
||||
!dragStartMouse ||
|
||||
!transformState
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Throttle position updates using requestAnimationFrame for better performance
|
||||
if (rafId !== null) return // Skip if frame already scheduled
|
||||
|
||||
rafId = requestAnimationFrame(() => {
|
||||
rafId = null
|
||||
|
||||
if (!dragStartPos || !dragStartMouse || !transformState) return
|
||||
|
||||
// Calculate mouse delta in screen coordinates
|
||||
const mouseDelta = {
|
||||
x: event.clientX - dragStartMouse.x,
|
||||
y: event.clientY - dragStartMouse.y
|
||||
}
|
||||
|
||||
// Convert to canvas coordinates
|
||||
const canvasOrigin = transformState.screenToCanvas({ x: 0, y: 0 })
|
||||
const canvasWithDelta = transformState.screenToCanvas(mouseDelta)
|
||||
const canvasDelta = {
|
||||
x: canvasWithDelta.x - canvasOrigin.x,
|
||||
y: canvasWithDelta.y - canvasOrigin.y
|
||||
}
|
||||
|
||||
// Calculate new position for the current node
|
||||
const newPosition = {
|
||||
x: dragStartPos.x + canvasDelta.x,
|
||||
y: dragStartPos.y + canvasDelta.y
|
||||
}
|
||||
|
||||
// Apply mutation through the layout system (Vue batches DOM updates automatically)
|
||||
mutations.moveNode(nodeId, newPosition)
|
||||
|
||||
// If we're dragging multiple selected nodes, move them all together
|
||||
if (
|
||||
otherSelectedNodesStartPositions &&
|
||||
otherSelectedNodesStartPositions.size > 0
|
||||
) {
|
||||
for (const [
|
||||
otherNodeId,
|
||||
startPos
|
||||
] of otherSelectedNodesStartPositions) {
|
||||
const newOtherPosition = {
|
||||
x: startPos.x + canvasDelta.x,
|
||||
y: startPos.y + canvasDelta.y
|
||||
}
|
||||
mutations.moveNode(otherNodeId, newOtherPosition)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* End dragging
|
||||
*/
|
||||
function endDrag(event: PointerEvent) {
|
||||
if (!isDragging.value) return
|
||||
|
||||
// Apply snap to final position if snap was active (matches LiteGraph behavior)
|
||||
if (shouldSnap(event)) {
|
||||
const boundsUpdates: NodeBoundsUpdate[] = []
|
||||
|
||||
// Snap main node
|
||||
const currentLayout = layoutStore.getNodeLayoutRef(nodeId).value
|
||||
if (currentLayout) {
|
||||
const currentPos = currentLayout.position
|
||||
const snappedPos = applySnapToPosition({ ...currentPos })
|
||||
|
||||
// Only add update if position actually changed
|
||||
if (snappedPos.x !== currentPos.x || snappedPos.y !== currentPos.y) {
|
||||
boundsUpdates.push({
|
||||
nodeId,
|
||||
bounds: {
|
||||
x: snappedPos.x,
|
||||
y: snappedPos.y,
|
||||
width: currentLayout.size.width,
|
||||
height: currentLayout.size.height
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Also snap other selected nodes
|
||||
// Capture all positions at the start to ensure consistent state
|
||||
if (
|
||||
otherSelectedNodesStartPositions &&
|
||||
otherSelectedNodesStartPositions.size > 0
|
||||
) {
|
||||
for (const otherNodeId of otherSelectedNodesStartPositions.keys()) {
|
||||
const nodeLayout = layoutStore.getNodeLayoutRef(otherNodeId).value
|
||||
if (nodeLayout) {
|
||||
const currentPos = { ...nodeLayout.position }
|
||||
const snappedPos = applySnapToPosition(currentPos)
|
||||
|
||||
// Only add update if position actually changed
|
||||
if (
|
||||
snappedPos.x !== currentPos.x ||
|
||||
snappedPos.y !== currentPos.y
|
||||
) {
|
||||
boundsUpdates.push({
|
||||
nodeId: otherNodeId,
|
||||
bounds: {
|
||||
x: snappedPos.x,
|
||||
y: snappedPos.y,
|
||||
width: nodeLayout.size.width,
|
||||
height: nodeLayout.size.height
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply all snap updates in a single batched transaction
|
||||
if (boundsUpdates.length > 0) {
|
||||
layoutStore.batchUpdateNodeBounds(boundsUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
isDragging.value = false
|
||||
dragStartPos = null
|
||||
dragStartMouse = null
|
||||
otherSelectedNodesStartPositions = null
|
||||
|
||||
// Stop tracking shift key state
|
||||
stopShiftSync?.()
|
||||
stopShiftSync = null
|
||||
|
||||
// Cancel any pending animation frame
|
||||
if (rafId !== null) {
|
||||
cancelAnimationFrame(rafId)
|
||||
rafId = null
|
||||
}
|
||||
|
||||
// Release pointer
|
||||
if (!(event.target instanceof HTMLElement)) return
|
||||
event.target.releasePointerCapture(event.pointerId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Update node position directly (without drag)
|
||||
*/
|
||||
@@ -260,33 +39,11 @@ export function useNodeLayout(nodeIdMaybe: MaybeRefOrGetter<string>) {
|
||||
|
||||
return {
|
||||
// Reactive state (via customRef)
|
||||
layoutRef,
|
||||
position,
|
||||
size,
|
||||
bounds,
|
||||
isVisible,
|
||||
zIndex,
|
||||
isDragging,
|
||||
|
||||
// Mutations
|
||||
moveNodeTo,
|
||||
|
||||
// Drag handlers
|
||||
startDrag,
|
||||
handleDrag,
|
||||
endDrag,
|
||||
|
||||
// Computed styles for Vue templates
|
||||
nodeStyle: computed(
|
||||
(): CSSProperties => ({
|
||||
position: 'absolute' as const,
|
||||
left: `${position.value.x}px`,
|
||||
top: `${position.value.y}px`,
|
||||
width: `${size.value.width}px`,
|
||||
height: `${size.value.height}px`,
|
||||
zIndex: zIndex.value,
|
||||
cursor: isDragging.value ? 'grabbing' : 'grab'
|
||||
})
|
||||
)
|
||||
moveNodeTo
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,21 +82,11 @@ describe('WidgetButton Interactions', () => {
|
||||
expect(button.exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('renders widget label when name is provided', () => {
|
||||
it('renders widget text when name is provided', () => {
|
||||
const widget = createMockWidget()
|
||||
const wrapper = mountComponent(widget)
|
||||
|
||||
const label = wrapper.find('label')
|
||||
expect(label.exists()).toBe(true)
|
||||
expect(label.text()).toBe('test_button')
|
||||
})
|
||||
|
||||
it('does not render label when widget name is empty', () => {
|
||||
const widget = createMockWidget({}, undefined, '')
|
||||
const wrapper = mountComponent(widget)
|
||||
|
||||
const label = wrapper.find('label')
|
||||
expect(label.exists()).toBe(false)
|
||||
expect(wrapper.text()).toBe('test_button')
|
||||
})
|
||||
|
||||
it('sets button size to small', () => {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label v-if="widget.name" class="text-secondary text-sm">{{
|
||||
widget.name
|
||||
}}</label>
|
||||
<Button
|
||||
v-bind="filteredProps"
|
||||
:aria-label="widget.name || widget.label"
|
||||
size="small"
|
||||
@click="handleClick"
|
||||
/>
|
||||
>
|
||||
<template v-if="widget.name">
|
||||
{{ widget.name }}
|
||||
</template>
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ const renderedHtml = computed(() => {
|
||||
|
||||
// Methods
|
||||
const startEditing = async () => {
|
||||
if (isEditing.value) return
|
||||
if (isEditing.value || widget.options?.read_only) return
|
||||
|
||||
isEditing.value = true
|
||||
await nextTick()
|
||||
|
||||
@@ -136,8 +136,8 @@ const outputItems = computed<DropdownItem[]>(() => {
|
||||
})
|
||||
})
|
||||
|
||||
return Array.from(outputs).map((output, index) => ({
|
||||
id: `output-${index}`,
|
||||
return Array.from(outputs).map((output) => ({
|
||||
id: `output-${output}`,
|
||||
mediaSrc: getMediaUrl(output.replace(' [output]', ''), 'output'),
|
||||
name: output,
|
||||
label: getDisplayLabel(output),
|
||||
@@ -215,16 +215,14 @@ const layoutMode = ref<LayoutMode>(props.defaultLayoutMode ?? 'grid')
|
||||
watch(
|
||||
modelValue,
|
||||
(currentValue) => {
|
||||
if (currentValue !== undefined) {
|
||||
const item = dropdownItems.value.find(
|
||||
(item) => item.name === currentValue
|
||||
)
|
||||
if (item) {
|
||||
selectedSet.value.clear()
|
||||
selectedSet.value.add(item.id)
|
||||
}
|
||||
} else {
|
||||
if (currentValue === undefined) {
|
||||
selectedSet.value.clear()
|
||||
return
|
||||
}
|
||||
const item = dropdownItems.value.find((item) => item.name === currentValue)
|
||||
if (item) {
|
||||
selectedSet.value.clear()
|
||||
selectedSet.value.add(item.id)
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
:disabled="widget.options?.read_only"
|
||||
fluid
|
||||
data-capture-wheel="true"
|
||||
@pointerdown.capture.stop
|
||||
@pointermove.capture.stop
|
||||
@pointerup.capture.stop
|
||||
@contextmenu.capture.stop
|
||||
/>
|
||||
<LODFallback />
|
||||
</div>
|
||||
|
||||
@@ -32,24 +32,13 @@ const selectedItems = computed(() => {
|
||||
return props.items.filter((item) => props.selected.has(item.id))
|
||||
})
|
||||
|
||||
const chevronClass = computed(() =>
|
||||
cn(
|
||||
'mr-2 size-4 transition-transform duration-200 flex-shrink-0 text-component-node-foreground-secondary',
|
||||
{
|
||||
'rotate-180': props.isOpen
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
const theButtonStyle = computed(() =>
|
||||
cn(
|
||||
'border-0 bg-component-node-widget-background outline-none text-text-secondary',
|
||||
{
|
||||
'hover:bg-component-node-widget-background-hovered cursor-pointer':
|
||||
!props.disabled,
|
||||
'cursor-not-allowed': props.disabled,
|
||||
'text-text-primary': selectedItems.value.length > 0
|
||||
}
|
||||
props.disabled
|
||||
? 'cursor-not-allowed'
|
||||
: 'hover:bg-component-node-widget-background-hovered cursor-pointer',
|
||||
selectedItems.value.length > 0 && 'text-text-primary'
|
||||
)
|
||||
)
|
||||
</script>
|
||||
@@ -78,13 +67,21 @@ const theButtonStyle = computed(() =>
|
||||
>
|
||||
<span class="min-w-0 flex-1 px-1 py-2 text-left truncate">
|
||||
<span v-if="!selectedItems.length">
|
||||
{{ props.placeholder }}
|
||||
{{ placeholder }}
|
||||
</span>
|
||||
<span v-else>
|
||||
{{ selectedItems.map((item) => item.label ?? item.name).join(', ') }}
|
||||
</span>
|
||||
</span>
|
||||
<i class="icon-[lucide--chevron-down]" :class="chevronClass" />
|
||||
<i
|
||||
class="icon-[lucide--chevron-down]"
|
||||
:class="
|
||||
cn(
|
||||
'mr-2 size-4 transition-transform duration-200 flex-shrink-0 text-component-node-foreground-secondary',
|
||||
isOpen && 'rotate-180'
|
||||
)
|
||||
"
|
||||
/>
|
||||
</button>
|
||||
<!-- Open File -->
|
||||
<label
|
||||
|
||||
@@ -38,6 +38,7 @@ const getDefaultValue = (inputSpec: ComboInputSpec) => {
|
||||
// Map node types to expected media types
|
||||
const NODE_MEDIA_TYPE_MAP: Record<string, 'image' | 'video' | 'audio'> = {
|
||||
LoadImage: 'image',
|
||||
LoadImageOutput: 'image',
|
||||
LoadVideo: 'video',
|
||||
LoadAudio: 'audio'
|
||||
}
|
||||
@@ -45,6 +46,7 @@ const NODE_MEDIA_TYPE_MAP: Record<string, 'image' | 'video' | 'audio'> = {
|
||||
// Map node types to placeholder i18n keys
|
||||
const NODE_PLACEHOLDER_MAP: Record<string, string> = {
|
||||
LoadImage: 'widgets.uploadSelect.placeholderImage',
|
||||
LoadImageOutput: 'widgets.uploadSelect.placeholderImage',
|
||||
LoadVideo: 'widgets.uploadSelect.placeholderVideo',
|
||||
LoadAudio: 'widgets.uploadSelect.placeholderAudio'
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { ComponentWidgetImpl, addWidget } from '@/scripts/domWidget'
|
||||
import type { ComponentWidgetStandardProps } from '@/scripts/domWidget'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
|
||||
type TextPreviewCustomProps = Omit<
|
||||
InstanceType<typeof TextPreviewWidget>['$props'],
|
||||
@@ -14,15 +15,15 @@ type TextPreviewCustomProps = Omit<
|
||||
|
||||
const PADDING = 16
|
||||
|
||||
export const useTextPreviewWidget = (
|
||||
export function useTextPreviewWidget(
|
||||
options: {
|
||||
minHeight?: number
|
||||
} = {}
|
||||
) => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
): ComfyWidgetConstructorV2 {
|
||||
function widgetConstructor(
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
): IBaseWidget {
|
||||
const widgetValue = ref<string>('')
|
||||
const widget = new ComponentWidgetImpl<
|
||||
string | object,
|
||||
@@ -41,8 +42,10 @@ export const useTextPreviewWidget = (
|
||||
widgetValue.value = typeof value === 'string' ? value : String(value)
|
||||
},
|
||||
getMinHeight: () => options.minHeight ?? 42 + PADDING,
|
||||
serialize: false
|
||||
}
|
||||
serialize: false,
|
||||
read_only: true
|
||||
},
|
||||
type: inputSpec.type
|
||||
})
|
||||
addWidget(node, widget)
|
||||
return widget
|
||||
|
||||
@@ -236,9 +236,7 @@ export function useRemoteWidget<
|
||||
* Add a refresh button to the node that, when clicked, will force the widget to refresh
|
||||
*/
|
||||
function addRefreshButton() {
|
||||
node.addWidget('button', 'refresh', 'refresh', widget.refresh, {
|
||||
canvasOnly: true
|
||||
})
|
||||
node.addWidget('button', 'refresh', 'refresh', widget.refresh)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -263,8 +261,7 @@ export function useRemoteWidget<
|
||||
autoRefreshEnabled = value
|
||||
},
|
||||
{
|
||||
serialize: false,
|
||||
canvasOnly: true
|
||||
serialize: false
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user