comfy-ts 2.20.2 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +17 -1
  2. package/dist/{ServeApp-B469W26E.js → ServeApp-DuxYdaZZ.js} +142 -7
  3. package/dist/ServeApp-DuxYdaZZ.js.map +1 -0
  4. package/dist/cli.js +5 -5
  5. package/dist/{exampleAssets-yBLaKXLq.js → exampleAssets-1NHndnNB.js} +59 -17
  6. package/dist/exampleAssets-1NHndnNB.js.map +1 -0
  7. package/dist/{findDefinedWorkflow-B90-xFxX.js → findDefinedWorkflow-CRsBTTJK.js} +2 -2
  8. package/dist/{findDefinedWorkflow-B90-xFxX.js.map → findDefinedWorkflow-CRsBTTJK.js.map} +1 -1
  9. package/dist/index.cjs +118 -19
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +90 -9
  12. package/dist/index.d.ts +90 -9
  13. package/dist/index.js +117 -20
  14. package/dist/index.js.map +1 -1
  15. package/dist/{run-run-C-dDD9Dc.js → run-run-Y5ZI48vV.js} +5 -5
  16. package/dist/{run-run-C-dDD9Dc.js.map → run-run-Y5ZI48vV.js.map} +1 -1
  17. package/dist/{run-serve-CsEYPGm9.js → run-serve-CICU_wTL.js} +4 -4
  18. package/dist/{run-serve-CsEYPGm9.js.map → run-serve-CICU_wTL.js.map} +1 -1
  19. package/dist/{run-tui-bsmja4hi.js → run-tui-CViJXsHL.js} +4 -4
  20. package/dist/{run-tui-bsmja4hi.js.map → run-tui-CViJXsHL.js.map} +1 -1
  21. package/dist/{schemaDrift-DaWsE-mt.js → schemaDrift-CzjaIwZX.js} +53 -20
  22. package/dist/schemaDrift-CzjaIwZX.js.map +1 -0
  23. package/dist/serve-web.js +204 -47
  24. package/dist/web.d.ts +90 -9
  25. package/dist/web.js +117 -20
  26. package/dist/web.js.map +1 -1
  27. package/examples/README.md +2 -0
  28. package/examples/depth-explorer/models.ts +722 -0
  29. package/examples/depth-explorer/serve.ts +140 -0
  30. package/examples/depth-explorer/thumbs/bae.webp +0 -0
  31. package/examples/depth-explorer/thumbs/da3-mono-large.webp +0 -0
  32. package/examples/depth-explorer/thumbs/dav1-vitl.webp +0 -0
  33. package/examples/depth-explorer/thumbs/dav2-vitl.webp +0 -0
  34. package/examples/depth-explorer/thumbs/dsine.webp +0 -0
  35. package/examples/depth-explorer/thumbs/iid-albedo.webp +0 -0
  36. package/examples/depth-explorer/thumbs/iid-metalness.webp +0 -0
  37. package/examples/depth-explorer/thumbs/iid-roughness.webp +0 -0
  38. package/examples/depth-explorer/thumbs/iid-shading.webp +0 -0
  39. package/examples/depth-explorer/thumbs/iid-specular.webp +0 -0
  40. package/examples/depth-explorer/thumbs/leres.webp +0 -0
  41. package/examples/depth-explorer/thumbs/lotus-depth.webp +0 -0
  42. package/examples/depth-explorer/thumbs/marigold2-albedo.webp +0 -0
  43. package/examples/depth-explorer/thumbs/marigold2-depth.webp +0 -0
  44. package/examples/depth-explorer/thumbs/marigold2-normal.webp +0 -0
  45. package/examples/depth-explorer/thumbs/metric3d-depth.webp +0 -0
  46. package/examples/depth-explorer/thumbs/metric3d-normal.webp +0 -0
  47. package/examples/depth-explorer/thumbs/midas-normal.webp +0 -0
  48. package/examples/depth-explorer/thumbs/midas.webp +0 -0
  49. package/examples/depth-explorer/thumbs/moge2-depth.webp +0 -0
  50. package/examples/depth-explorer/thumbs/moge2-normal.webp +0 -0
  51. package/examples/depth-explorer/thumbs/zoe-da.webp +0 -0
  52. package/examples/depth-explorer/thumbs/zoe.webp +0 -0
  53. package/examples/depth-explorer/web/App.tsx +457 -0
  54. package/examples/depth-explorer/web/gl.ts +202 -0
  55. package/examples/depth-explorer/web/index.html +14 -0
  56. package/examples/depth-explorer/web/main.tsx +19 -0
  57. package/examples/depth-explorer/web/pixels.ts +86 -0
  58. package/examples/depth-explorer/web/state.ts +329 -0
  59. package/examples/depth-explorer/web/styles.css +366 -0
  60. package/examples/depth-explorer/web/tsconfig.json +16 -0
  61. package/examples/rvion/17-relight.cflow.ts +110 -0
  62. package/package.json +3 -2
  63. package/src/cli/serve/ServeApp.ts +79 -4
  64. package/src/cli/serve/describeVar.ts +12 -1
  65. package/src/cli/serve/resultHistory.ts +6 -1
  66. package/src/cli/serve/thumbs.ts +66 -0
  67. package/src/cli/serve/web/api.ts +5 -1
  68. package/src/cli/serve/web/components/Gallery.tsx +2 -0
  69. package/src/cli/serve/web/components/controls/BasicControls.tsx +14 -17
  70. package/src/cli/serve/web/components/controls/MediaControl.tsx +62 -9
  71. package/src/cli/serve/web/components/controls/RichSelect.tsx +262 -0
  72. package/src/cli/serve/web/state/RunSt.poll.test.ts +4 -1
  73. package/src/cli/serve/web/state/choiceButtons.ts +26 -2
  74. package/src/cli/serve/web/styles.ts +39 -0
  75. package/src/cli/serve/web/widgets/OutputWidgets.tsx +19 -0
  76. package/src/cli/serve/web/widgets/RelightSt.ts +113 -0
  77. package/src/cli/serve/web/widgets/RelightWidget.tsx +305 -0
  78. package/src/cli/serve/web/widgets/relightGl.ts +305 -0
  79. package/src/cli/serve/web/widgets/widgetStyles.ts +19 -0
  80. package/src/coreExports.ts +9 -0
  81. package/src/host/ComfyHost.ts +21 -0
  82. package/src/host/leastBusy.ts +37 -0
  83. package/src/state.ts +6 -0
  84. package/src/vars/ComfyVars.ts +32 -2
  85. package/src/vars/DefinedWorkflow.ts +42 -21
  86. package/src/vars/outputWidgets.ts +47 -0
  87. package/dist/ServeApp-B469W26E.js.map +0 -1
  88. package/dist/exampleAssets-yBLaKXLq.js.map +0 -1
  89. package/dist/schemaDrift-DaWsE-mt.js.map +0 -1
@@ -70,8 +70,13 @@ export type VarDescriptor = {
70
70
  /** size: preset labels starred by default (quick buttons before the list) */
71
71
  starredPresets?: string[]
72
72
  extensions?: readonly string[]
73
+ /** image, audio, video: one-click starting files. `thumb` (a url the page can show) and
74
+ * `missing` (a local file not on this machine) are filled by ServeApp.describeModule */
75
+ mediaPresets?: MediaPresetDescriptor[]
73
76
  }
74
77
 
78
+ export type MediaPresetDescriptor = { label: string; value: string; thumb?: string; missing?: boolean }
79
+
75
80
  /** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
76
81
  function presetsOrUndefined(presets: VarPreset[]): VarPreset[] | undefined {
77
82
  return presets.length === 0 ? undefined : presets
@@ -166,7 +171,13 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
166
171
  case 'audio':
167
172
  case 'video': {
168
173
  const v = varDef as MediaVar
169
- return { ...base, payload: 'local file path or http(s) url', extensions: v.extensions }
174
+ const presets = v.presets
175
+ return {
176
+ ...base,
177
+ payload: 'local file path or http(s) url',
178
+ extensions: v.extensions,
179
+ ...(presets.length > 0 ? { mediaPresets: presets } : {}),
180
+ }
170
181
  }
171
182
  default: {
172
183
  // an unknown kind CAN reach here: a globally installed cli against a project on a
@@ -2,7 +2,10 @@
2
2
  // again. Unsaved outputs keep their bytes here, the ONLY copy, under one byte budget, FIFO.
3
3
  // Nothing is written to disk: a server restart forgets it all. PURE, headless-tested
4
4
 
5
- export type RunOutput = { filename: string; url: string | null; absPath: string | null }
5
+ import type { OutputWidget } from 'src/vars/outputWidgets.ts'
6
+
7
+ /** `tags`: the save node's metadata tags, which output widgets read (absent on older records) */
8
+ export type RunOutput = { filename: string; url: string | null; absPath: string | null; tags?: string[] }
6
9
  export type RunAudioOutput = RunOutput & { mime: string }
7
10
 
8
11
  /** the run reply `POST /generate` answers, and what `GET /results` lists */
@@ -21,6 +24,8 @@ export type RunRecord = {
21
24
  audios: RunAudioOutput[]
22
25
  /** absent on a record from an older server */
23
26
  videos?: RunAudioOutput[]
27
+ /** the module's output widgets at run time, so a kept result draws them after a reload */
28
+ widgets?: OutputWidget[]
24
29
  }
25
30
 
26
31
  export type MemoryUsage = { usedBytes: number; budgetBytes: number; outputs: number; runs: number }
@@ -0,0 +1,66 @@
1
+ // small previews of LOCAL images for the panel: a choice option's thumb, a media preset, the
2
+ // current value of an image var. Not a file server: a path is served only when a served module
3
+ // declared it (a thumb, a preset, a default) or it lies under an allowed root (the output root,
4
+ // a served module's folder). An http(s) image is never proxied: the page loads it itself.
5
+ import { existsSync, statSync } from 'node:fs'
6
+ import { resolve } from 'pathe'
7
+ import { importSharp } from 'src/utils/lazySharp.ts'
8
+
9
+ export const isHttpUrl = (s: string): boolean => /^https?:\/\//i.test(s)
10
+
11
+ /** the url the page loads for a local image's preview */
12
+ export function thumbUrl(abs: string, width = 160): string {
13
+ return `/thumb?src=${encodeURIComponent(abs)}&w=${width}`
14
+ }
15
+
16
+ const MAX_WIDTH = 640
17
+ const MAX_CACHED = 400
18
+
19
+ export class ThumbStore {
20
+ private allowed = new Set<string>()
21
+ private roots = new Set<string>()
22
+ private cache = new Map<string, Uint8Array>()
23
+
24
+ /** one file a served module declared */
25
+ allow(abs: string): void {
26
+ this.allowed.add(resolve(abs))
27
+ }
28
+
29
+ /** every image under this folder */
30
+ allowRoot(dir: string): void {
31
+ this.roots.add(resolve(dir))
32
+ }
33
+
34
+ isAllowed(abs: string): boolean {
35
+ const p = resolve(abs)
36
+ if (this.allowed.has(p)) return true
37
+ for (const root of this.roots) if (p.startsWith(`${root}/`)) return true
38
+ return false
39
+ }
40
+
41
+ /** a webp at most `width` wide, or why not: 'forbidden' (not declared, not under a root),
42
+ * 'missing' (not on this machine) */
43
+ async render(abs: string, width: number): Promise<Uint8Array | 'forbidden' | 'missing'> {
44
+ if (!this.isAllowed(abs)) return 'forbidden'
45
+ const p = resolve(abs)
46
+ if (!existsSync(p)) return 'missing'
47
+ const w = Math.max(16, Math.min(MAX_WIDTH, Math.round(width)))
48
+ const key = `${p}|${statSync(p).mtimeMs}|${w}`
49
+ const hit = this.cache.get(key)
50
+ if (hit != null) return hit
51
+ const sharp = await importSharp('a thumbnail')
52
+ const bytes = new Uint8Array(
53
+ await sharp(p)
54
+ .rotate()
55
+ .resize({ width: w, height: w, fit: 'inside', withoutEnlargement: true })
56
+ .webp({ quality: 78 })
57
+ .toBuffer(),
58
+ )
59
+ if (this.cache.size >= MAX_CACHED) {
60
+ const oldest = this.cache.keys().next().value
61
+ if (oldest != null) this.cache.delete(oldest)
62
+ }
63
+ this.cache.set(key, bytes)
64
+ return bytes
65
+ }
66
+ }
@@ -1,6 +1,7 @@
1
1
  // typed fetch layer over the serve json api — the ONLY web-ui module that talks http
2
2
  import type { LlmConfigEntry } from 'src/cli/serve/llmConfigShape.ts'
3
3
  import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
4
+ import type { OutputWidget } from 'src/vars/outputWidgets.ts'
4
5
 
5
6
  export type ModuleDescription = {
6
7
  module: string
@@ -24,7 +25,8 @@ export type IndexPayload = {
24
25
  loadErrors?: Record<string, string>
25
26
  }
26
27
 
27
- export type GeneratedImage = { filename: string; url: string | null; absPath: string | null }
28
+ /** `tags`: the save node's metadata tags, read by output widgets */
29
+ export type GeneratedImage = { filename: string; url: string | null; absPath: string | null; tags?: string[] }
28
30
 
29
31
  /** a STRING output (PreviewAny). An llm graph produces these and no images at all */
30
32
  export type GeneratedText = { nodeKey: string | null; text: string }
@@ -48,6 +50,8 @@ export type GenerateOk = {
48
50
  texts?: GeneratedText[]
49
51
  audios?: GeneratedAudio[]
50
52
  videos?: GeneratedVideo[]
53
+ /** the module's output widgets (`widget.relight(...)`), drawn over this run's tagged images */
54
+ widgets?: OutputWidget[]
51
55
  }
52
56
 
53
57
  async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
@@ -15,6 +15,7 @@ import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
15
15
  import { MOD_KEY } from 'src/cli/serve/web/components/modKey.ts'
16
16
  import { SHORTCUT_KEYS } from 'src/cli/serve/web/state/shortcuts.ts'
17
17
  import { onEscape } from 'src/cli/serve/web/state/escape.ts'
18
+ import { OutputWidgets } from 'src/cli/serve/web/widgets/OutputWidgets.tsx'
18
19
 
19
20
  /** on an output only the serve process holds: a restart, or the memory budget, loses it */
20
21
  function EphemeralPill(p: { out: { url: string | null; absPath: string | null } }): ReactNode {
@@ -520,6 +521,7 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
520
521
  <Icon name="trash" />
521
522
  </button>
522
523
  </div>
524
+ <OutputWidgets widgets={r.widgets} images={r.images} />
523
525
  <div className="imgs">
524
526
  {r.images.map((img, ix) =>
525
527
  img.url != null ? (
@@ -2,8 +2,9 @@
2
2
  // bigger kinds (prompt, seed, size, loras, image) have their own files
3
3
  import { observer } from 'mobx-react-lite'
4
4
  import { PresetPicker } from 'src/cli/serve/web/components/controls/PresetPicker.tsx'
5
+ import { RichSelect } from 'src/cli/serve/web/components/controls/RichSelect.tsx'
5
6
  import { VarIcon } from 'src/cli/serve/web/components/VarIcon.tsx'
6
- import { choiceAsButtons, clickChoice, pickedChoices } from 'src/cli/serve/web/state/choiceButtons.ts'
7
+ import { choiceAsButtons, clickChoice, hasRichLook, pickedChoices } from 'src/cli/serve/web/state/choiceButtons.ts'
7
8
  import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
8
9
 
9
10
  export const TextControl = observer(function TextControl(p: { v: VarSt }) {
@@ -102,7 +103,11 @@ export const ChoiceControl = observer(function ChoiceControl(p: { v: VarSt }) {
102
103
  <span className="hint">(unset)</span>
103
104
  ) : null
104
105
  // many choices can always be several buttons at once: a select holds one value only
105
- if (choiceAsButtons(choices) || select !== 'one')
106
+ if (
107
+ choiceAsButtons(choices, looks) ||
108
+ select === 'many' ||
109
+ (select === 'zero-or-one' && !hasRichLook(choices, looks))
110
+ )
106
111
  return (
107
112
  <span className="row-inline">
108
113
  <span className="btn-group wrap">
@@ -140,21 +145,13 @@ export const ChoiceControl = observer(function ChoiceControl(p: { v: VarSt }) {
140
145
  {staleNote}
141
146
  </span>
142
147
  )
143
- const value = picked[0] ?? ''
144
148
  return (
145
- <select value={value} onChange={(e) => p.v.set(e.target.value)}>
146
- {/* honest display for a value outside the current union (stale draft): the
147
- browser would silently SHOW the first option while the state differs */}
148
- {choices.includes(value) ? null : (
149
- <option value={value} disabled>
150
- {value === '' ? '(unset)' : `${value} (not on this host)`}
151
- </option>
152
- )}
153
- {choices.map((c) => (
154
- <option key={c} value={c}>
155
- {c}
156
- </option>
157
- ))}
158
- </select>
149
+ <RichSelect
150
+ choices={choices}
151
+ value={picked[0] ?? (select === 'zero-or-one' ? null : '')}
152
+ looks={looks}
153
+ allowNone={select === 'zero-or-one'}
154
+ onPick={(c) => p.v.set(c)}
155
+ />
159
156
  )
160
157
  })
@@ -1,9 +1,12 @@
1
1
  // image, audio, video: a path/url input the api already accepts, a browser upload (POST /upload
2
2
  // → local file under outputs/serve-inputs/), and a DROP ZONE for desktop files and gallery
3
- // outputs. The preview plays the var's own medium when the value has a browser url
3
+ // outputs. The preview plays the var's own medium: a url as is, a local image through GET /thumb
4
+ // (which only serves what a served workflow declared, or what lies under its folder or the
5
+ // outputs). The workflow's presets are one-click tiles; one not on this machine is disabled
4
6
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
5
7
  import { observer } from 'mobx-react-lite'
6
- import { useRef, useState, type DragEvent, type ReactNode } from 'react'
8
+ import { useEffect, useRef, useState, type DragEvent, type ReactNode } from 'react'
9
+ import type { MediaPresetDescriptor } from 'src/cli/serve/describeVar.ts'
7
10
  import { decodeDraggedOutput, OUTPUT_DRAG_MIME } from 'src/cli/serve/web/state/mediaDrop.ts'
8
11
  import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
9
12
  import type { MediaKind } from 'src/runner/mediaKinds.ts'
@@ -14,17 +17,51 @@ function isMediaDrag(e: DragEvent): boolean {
14
17
  return types.includes(OUTPUT_DRAG_MIME) || types.includes('Files')
15
18
  }
16
19
 
17
- function Preview(p: { kind: MediaKind; url: string; alt: string }): ReactNode {
18
- if (p.kind === 'audio') return <audio controls preload="metadata" src={p.url} />
19
- if (p.kind === 'video') return <video controls muted preload="metadata" src={p.url} />
20
- return <img src={p.url} alt={p.alt} />
20
+ function Preview(p: { kind: MediaKind; url: string; alt: string; onError: () => void }): ReactNode {
21
+ if (p.kind === 'audio') return <audio controls preload="metadata" src={p.url} onError={p.onError} />
22
+ if (p.kind === 'video') return <video controls muted preload="metadata" src={p.url} onError={p.onError} />
23
+ return <img src={p.url} alt={p.alt} onError={p.onError} />
24
+ }
25
+
26
+ /** the workflow's starting files: a thumbnail and a name each, one click to use it */
27
+ function Presets(p: { presets: MediaPresetDescriptor[]; value: string; onPick: (value: string) => void }): ReactNode {
28
+ return (
29
+ <div className="media-presets">
30
+ {p.presets.map((preset) => (
31
+ <button
32
+ key={preset.label}
33
+ type="button"
34
+ className={`media-preset${preset.value === p.value ? ' sel' : ''}`}
35
+ disabled={preset.missing === true}
36
+ data-tip={
37
+ preset.missing === true ? `${preset.label}: not on this machine (${preset.value})` : preset.value
38
+ }
39
+ onClick={() => p.onPick(preset.value)}
40
+ >
41
+ {preset.thumb != null ? (
42
+ <img src={preset.thumb} alt="" loading="lazy" />
43
+ ) : (
44
+ <span className="media-preset-none" />
45
+ )}
46
+ <span>{preset.label}</span>
47
+ </button>
48
+ ))}
49
+ </div>
50
+ )
21
51
  }
22
52
 
23
53
  export const MediaControl = observer(function MediaControl(p: { v: VarSt; kind: MediaKind }) {
24
54
  const fileInput = useRef<HTMLInputElement>(null)
25
55
  const [over, setOver] = useState(false)
26
56
  const value = typeof p.v.value === 'string' ? p.v.value : ''
27
- const previewUrl = /^https?:\/\//.test(value) ? value : p.v.uploadedUrl
57
+ const isUrl = /^https?:\/\//.test(value)
58
+ const localThumb =
59
+ p.kind === 'image' && value !== '' && !isUrl ? `/thumb?src=${encodeURIComponent(value)}&w=360` : null
60
+ const previewUrl = isUrl ? value : (p.v.uploadedUrl ?? localThumb)
61
+ // a local file /thumb refuses (outside the workflow's folders) says so instead of a broken image
62
+ const [previewFailed, setPreviewFailed] = useState(false)
63
+ useEffect(() => setPreviewFailed(false), [previewUrl])
64
+ const presets = p.v.desc.mediaPresets ?? []
28
65
  const extensions = p.v.desc.extensions ?? []
29
66
  const onDrop = (e: DragEvent): void => {
30
67
  if (!isMediaDrag(e)) return
@@ -100,10 +137,26 @@ export const MediaControl = observer(function MediaControl(p: { v: VarSt; kind:
100
137
  <div className="hint media-drop-hint">
101
138
  drop a {p.kind} file here, or drag one from the results (or use its <b>→ {p.v.name}</b> button)
102
139
  </div>
140
+ {presets.length > 0 ? (
141
+ <Presets
142
+ presets={presets}
143
+ value={value}
144
+ onPick={(v) => {
145
+ p.v.set(v)
146
+ p.v.setUploadedUrl(null)
147
+ p.v.setMediaError(null)
148
+ }}
149
+ />
150
+ ) : null}
103
151
  {p.v.mediaError != null ? <div className="error">{p.v.mediaError}</div> : null}
104
- {previewUrl != null && previewUrl !== '' ? (
152
+ {previewUrl != null && previewUrl !== '' && !previewFailed ? (
105
153
  <div className={`img-preview media-preview-${p.kind}`}>
106
- <Preview kind={p.kind} url={previewUrl} alt={value} />
154
+ <Preview kind={p.kind} url={previewUrl} alt={value} onError={() => setPreviewFailed(true)} />
155
+ </div>
156
+ ) : null}
157
+ {previewFailed ? (
158
+ <div className="hint">
159
+ no preview: the panel shows files of the workflow's folders, the outputs and the presets
107
160
  </div>
108
161
  ) : null}
109
162
  </div>
@@ -0,0 +1,262 @@
1
+ // the panel's own dropdown for a single choice: each row its thumbnail, name, description,
2
+ // badges (date, size, speed, tags) and a 1..5 quality bar, read from `.ui({ options })`. A list
3
+ // longer than FILTER_FROM gets a filter box. Keys: arrows move, enter picks, escape closes,
4
+ // typing filters. A value outside the list (a stale draft) is said, never shown as an option.
5
+ // An optional choice (`select: 'zero-or-one'`) gets a first row « none », which picks null
6
+ import {
7
+ autoUpdate,
8
+ flip,
9
+ FloatingPortal,
10
+ offset,
11
+ shift,
12
+ size,
13
+ useDismiss,
14
+ useFloating,
15
+ useInteractions,
16
+ } from '@floating-ui/react'
17
+ import { observer, useLocalObservable } from 'mobx-react-lite'
18
+ import { useEffect, useRef, type KeyboardEvent, type ReactNode } from 'react'
19
+ import { VarIcon } from 'src/cli/serve/web/components/VarIcon.tsx'
20
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
21
+ import type { ChoiceOptionLook } from 'src/vars/ComfyVars.ts'
22
+
23
+ const FILTER_FROM = 8
24
+
25
+ function Quality(p: { value: number | undefined }): ReactNode {
26
+ if (p.value == null) return null
27
+ const q = Math.max(0, Math.min(5, Math.round(p.value)))
28
+ return (
29
+ <span className="rs-quality" data-tip={`quality ${q} of 5`}>
30
+ {[1, 2, 3, 4, 5].map((i) => (
31
+ <i key={i} className={i <= q ? 'on' : ''} />
32
+ ))}
33
+ </span>
34
+ )
35
+ }
36
+
37
+ function Badges(p: { look: ChoiceOptionLook | undefined }): ReactNode {
38
+ const l = p.look
39
+ if (l == null) return null
40
+ const items = [l.date, l.size, l.speed, ...(l.tags ?? [])].filter((x): x is string => x != null && x !== '')
41
+ if (items.length === 0 && l.quality == null) return null
42
+ return (
43
+ <span className="rs-badges">
44
+ {items.map((b) => (
45
+ <span key={b} className="rs-badge">
46
+ {b}
47
+ </span>
48
+ ))}
49
+ <Quality value={l.quality} />
50
+ </span>
51
+ )
52
+ }
53
+
54
+ function Thumb(p: { look: ChoiceOptionLook | undefined; big?: boolean }): ReactNode {
55
+ const cls = p.big === true ? 'rs-thumb big' : 'rs-thumb'
56
+ if (p.look?.thumb != null) return <img className={cls} src={p.look.thumb} alt="" loading="lazy" />
57
+ if (p.look?.icon != null)
58
+ return (
59
+ <span className={`${cls} icon`}>
60
+ <VarIcon icon={p.look.icon} color={p.look.color} />
61
+ </span>
62
+ )
63
+ return null
64
+ }
65
+
66
+ const nameOf = (value: string, look: ChoiceOptionLook | undefined): string => look?.label ?? value
67
+
68
+ /** the « none » row of an optional choice: a key no option can hold */
69
+ const NONE = '\u0000none'
70
+
71
+ export const RichSelect = observer(function RichSelect(p: {
72
+ choices: readonly string[]
73
+ /** null: nothing picked (an optional choice) */
74
+ value: string | null
75
+ looks: Record<string, ChoiceOptionLook>
76
+ /** an optional choice: the list starts with « none » */
77
+ allowNone?: boolean
78
+ onPick: (value: string | null) => void
79
+ }) {
80
+ const st = useLocalObservable(() => ({
81
+ open: false,
82
+ query: '',
83
+ active: 0,
84
+ setOpen(v: boolean) {
85
+ this.open = v
86
+ this.query = ''
87
+ },
88
+ setQuery(q: string) {
89
+ this.query = q
90
+ this.active = 0
91
+ },
92
+ setActive(i: number) {
93
+ this.active = i
94
+ },
95
+ }))
96
+ const { refs, floatingStyles, context } = useFloating({
97
+ open: st.open,
98
+ onOpenChange: (o) => st.setOpen(o),
99
+ placement: 'bottom-start',
100
+ middleware: [
101
+ offset(4),
102
+ flip(),
103
+ shift({ padding: 8 }),
104
+ size({
105
+ padding: 8,
106
+ apply({ availableHeight, rects, elements }) {
107
+ elements.floating.style.maxHeight = `${Math.max(180, availableHeight)}px`
108
+ elements.floating.style.minWidth = `${Math.max(360, rects.reference.width)}px`
109
+ },
110
+ }),
111
+ ],
112
+ whileElementsMounted: autoUpdate,
113
+ })
114
+ const { getReferenceProps, getFloatingProps } = useInteractions([useDismiss(context)])
115
+ const filterRef = useRef<HTMLInputElement>(null)
116
+ const listRef = useRef<HTMLDivElement>(null)
117
+
118
+ const q = st.query.trim().toLowerCase()
119
+ const value = p.value ?? (p.allowNone === true ? NONE : '')
120
+ const rows = p.allowNone === true ? [NONE, ...p.choices] : p.choices
121
+ const shown = rows.filter((c) => {
122
+ if (q === '') return true
123
+ if (c === NONE) return 'none'.includes(q)
124
+ const l = p.looks[c]
125
+ return [c, l?.label, l?.description, ...(l?.tags ?? [])].some((s) => s?.toLowerCase().includes(q) === true)
126
+ })
127
+ const current = p.value == null ? undefined : p.looks[p.value]
128
+ const stale = value !== '' && value !== NONE && !p.choices.includes(value)
129
+
130
+ useEffect(() => {
131
+ if (!st.open) return
132
+ const ix = shown.indexOf(value)
133
+ st.setActive(ix >= 0 ? ix : 0)
134
+ if (p.choices.length >= FILTER_FROM) filterRef.current?.focus()
135
+ else listRef.current?.focus()
136
+ }, [st.open])
137
+ useEffect(() => {
138
+ listRef.current?.querySelector('.rs-row.active')?.scrollIntoView({ block: 'nearest' })
139
+ }, [st.active, st.open])
140
+
141
+ const pick = (c: string): void => {
142
+ p.onPick(c === NONE ? null : c)
143
+ st.setOpen(false)
144
+ }
145
+ const onKey = (e: KeyboardEvent): void => {
146
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
147
+ e.preventDefault()
148
+ const n = shown.length
149
+ if (n > 0) st.setActive((st.active + (e.key === 'ArrowDown' ? 1 : -1) + n) % n)
150
+ } else if (e.key === 'Enter') {
151
+ e.preventDefault()
152
+ const c = shown[st.active]
153
+ if (c != null) pick(c)
154
+ } else
155
+ onEscape(e, () => {
156
+ e.stopPropagation()
157
+ st.setOpen(false)
158
+ })
159
+ }
160
+
161
+ return (
162
+ <>
163
+ <button
164
+ type="button"
165
+ ref={refs.setReference}
166
+ className={st.open ? 'rs-trigger open' : 'rs-trigger'}
167
+ {...getReferenceProps({
168
+ onClick: () => st.setOpen(!st.open),
169
+ onKeyDown: (e) => {
170
+ if (!st.open && (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ')) {
171
+ e.preventDefault()
172
+ st.setOpen(true)
173
+ }
174
+ },
175
+ })}
176
+ >
177
+ <Thumb look={current} />
178
+ <span className="rs-trigger-text">
179
+ <span className="rs-name">
180
+ {value === NONE
181
+ ? 'none'
182
+ : value === ''
183
+ ? '(unset)'
184
+ : stale
185
+ ? `${value} (not on this host)`
186
+ : nameOf(value, current)}
187
+ </span>
188
+ {current?.label != null ? <span className="rs-value">{value}</span> : null}
189
+ </span>
190
+ <Badges look={current} />
191
+ <span className="rs-chevron">▾</span>
192
+ </button>
193
+ {st.open ? (
194
+ <FloatingPortal>
195
+ <div ref={refs.setFloating} style={floatingStyles} className="rs-pop" {...getFloatingProps()}>
196
+ {p.choices.length >= FILTER_FROM ? (
197
+ <input
198
+ ref={filterRef}
199
+ className="rs-filter"
200
+ placeholder={`filter ${p.choices.length} options`}
201
+ value={st.query}
202
+ onChange={(e) => st.setQuery(e.target.value)}
203
+ onKeyDown={onKey}
204
+ />
205
+ ) : null}
206
+ <div ref={listRef} className="rs-list" role="listbox" tabIndex={-1} onKeyDown={onKey}>
207
+ {shown.length === 0 ? <div className="rs-empty">nothing matches</div> : null}
208
+ {shown.map((c, i) => {
209
+ if (c === NONE)
210
+ return (
211
+ <div
212
+ key={c}
213
+ role="option"
214
+ aria-selected={value === NONE}
215
+ className={`rs-row rs-none${i === st.active ? ' active' : ''}${value === NONE ? ' sel' : ''}`}
216
+ onMouseEnter={() => st.setActive(i)}
217
+ onClick={() => pick(c)}
218
+ >
219
+ <span className="rs-thumb big icon">∅</span>
220
+ <span className="rs-row-text">
221
+ <span className="rs-name">none</span>
222
+ <span className="rs-desc">leave this out of the run</span>
223
+ </span>
224
+ {value === NONE ? <span className="rs-check">✓</span> : null}
225
+ </div>
226
+ )
227
+ const look = p.looks[c]
228
+ return (
229
+ <div
230
+ key={c}
231
+ role="option"
232
+ aria-selected={c === value}
233
+ className={`rs-row${i === st.active ? ' active' : ''}${c === value ? ' sel' : ''}`}
234
+ onMouseEnter={() => st.setActive(i)}
235
+ onClick={() => pick(c)}
236
+ >
237
+ <Thumb look={look} big />
238
+ <span className="rs-row-text">
239
+ <span className="rs-row-head">
240
+ <span className="rs-name">{nameOf(c, look)}</span>
241
+ {look?.label != null ? <span className="rs-value">{c}</span> : null}
242
+ </span>
243
+ {look?.description != null ? (
244
+ <span className="rs-desc">{look.description}</span>
245
+ ) : null}
246
+ <Badges look={look} />
247
+ </span>
248
+ {c === value ? <span className="rs-check">✓</span> : null}
249
+ </div>
250
+ )
251
+ })}
252
+ </div>
253
+ <div className="rs-foot">
254
+ {p.choices.length === 1 ? 'the only option on this host' : `${p.choices.length} options`} · ↑↓ ⏎
255
+ esc
256
+ </div>
257
+ </div>
258
+ </FloatingPortal>
259
+ ) : null}
260
+ </>
261
+ )
262
+ })
@@ -17,7 +17,10 @@ beforeEach(() => {
17
17
  return json({ running: true, percent: 50, hasPreview: true, previewSeq: statusReads })
18
18
  }
19
19
  if (url.startsWith('/generate/')) {
20
- await new Promise((r) => setTimeout(r, 400))
20
+ // the run ends once the panel read its status twice: a starved cpu delays the reads,
21
+ // it must not make the run end before them (the deadline keeps a broken poll red)
22
+ const deadline = Date.now() + 5000
23
+ while (statusReads < 2 && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10))
21
24
  return json({ promptId: 'p1', module: 'm', draft: 'd', seeds: {}, outputs: [] })
22
25
  }
23
26
  return json({ runs: [], memory: { usedBytes: 0, budgetBytes: 1, outputs: 0, runs: 0 } })
@@ -1,12 +1,36 @@
1
1
  // a choice var with a few short options renders as a row of buttons, every option visible and
2
- // one click away; anything longer stays a select. PURE, tests/serve-web-choice-buttons.test.ts
2
+ // one click away; anything longer, or any option the workflow describes, is the dropdown. PURE,
3
+ // tests/serve-web-choice-buttons.test.ts
4
+ import type { ChoiceOptionLook } from 'src/vars/ComfyVars.ts'
5
+
3
6
  export const MAX_BUTTONS = 5
4
7
  export const MAX_BUTTON_LABEL = 16
5
8
 
6
- export function choiceAsButtons(choices: readonly string[]): boolean {
9
+ export function choiceAsButtons(choices: readonly string[], looks: Record<string, ChoiceOptionLook> = {}): boolean {
10
+ // an option the workflow describes (a picture, a name, a quality…) needs the dropdown's rows to show it
11
+ if (hasRichLook(choices, looks)) return false
7
12
  return choices.length > 0 && choices.length <= MAX_BUTTONS && choices.every((c) => c.length <= MAX_BUTTON_LABEL)
8
13
  }
9
14
 
15
+ export function hasRichLook(choices: readonly string[], looks: Record<string, ChoiceOptionLook>): boolean {
16
+ return choices.some((c) => isRichLook(looks[c]))
17
+ }
18
+
19
+ /** more than a button can say: anything beyond an icon and a colour */
20
+ export function isRichLook(look: ChoiceOptionLook | undefined): boolean {
21
+ if (look == null) return false
22
+ return (
23
+ look.label != null ||
24
+ look.description != null ||
25
+ look.thumb != null ||
26
+ look.date != null ||
27
+ look.size != null ||
28
+ look.quality != null ||
29
+ look.speed != null ||
30
+ (look.tags?.length ?? 0) > 0
31
+ )
32
+ }
33
+
10
34
  export type ChoiceSelectMode = 'one' | 'zero-or-one' | 'many'
11
35
 
12
36
  /** the options picked right now, whatever the shape: one value, one or null, or a list */