comfy-ts 2.22.0 → 2.24.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 (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
@@ -0,0 +1,285 @@
1
+ // a pair of results, compared the way the hub's threads compare a before and an after (shipkit
2
+ // review-views.tsx): side by side, a curtain, an onion skin, the after alone with the before under
3
+ // the pointer, or only the pixels that changed. Every mode draws on the shared view, so a zoom on
4
+ // one side is the zoom on both.
5
+ import { observer } from 'mobx-react-lite'
6
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
7
+ import { timeOf } from '../../explorer-kit/web/ui.tsx'
8
+ import { COMPARE_MODES, type AppSt, type CompareMode } from './state.ts'
9
+ import { Layer, Viewport, ZoomBar, type Box } from './viewport.tsx'
10
+
11
+ const MODES: { mode: CompareMode; glyph: string; tip: string }[] = [
12
+ { mode: 'side', glyph: '◫', tip: 'side by side' },
13
+ { mode: 'swipe', glyph: '⇹', tip: 'curtain: drag the line, the before on the left, the after on the right' },
14
+ { mode: 'onion', glyph: '◐', tip: 'onion skin: the after over the before' },
15
+ { mode: 'mod', glyph: '▣', tip: 'the after alone: hovering the image shows the before' },
16
+ { mode: 'diff', glyph: '≠', tip: "only what changed: the after's changed pixels in colour, the rest faded" },
17
+ ]
18
+
19
+ /** a sum of channel differences under this is noise, as in the hub */
20
+ const DIFF_NOISE = 24
21
+
22
+ const changesWords = (share: number | null | undefined): string =>
23
+ share === undefined
24
+ ? 'reading…'
25
+ : share === null
26
+ ? 'could not be read'
27
+ : share === 0
28
+ ? 'none: no pixel differs'
29
+ : `${share < 0.001 ? '< 0.1' : (share * 100).toFixed(1)} % of the pixels`
30
+
31
+ type Diff = { canvas: HTMLCanvasElement; share: number }
32
+ const diffCache = new Map<string, Promise<Diff | null>>()
33
+
34
+ /** the after where it differs from the before, each changed pixel in its own colour and every other
35
+ * one a pale grey of it, at the results' size (the before is drawn at that size too) */
36
+ function diffOf(before: string, after: string, w: number, h: number): Promise<Diff | null> {
37
+ const key = `${before}|${after}`
38
+ let hit = diffCache.get(key)
39
+ if (hit == null) {
40
+ hit = (async (): Promise<Diff | null> => {
41
+ try {
42
+ const load = async (url: string): Promise<ImageBitmap> => createImageBitmap(await (await fetch(url)).blob())
43
+ const [a, b] = await Promise.all([load(before), load(after)])
44
+ const canvas = document.createElement('canvas')
45
+ canvas.width = w
46
+ canvas.height = h
47
+ const ctx = canvas.getContext('2d', { willReadFrequently: true })
48
+ if (ctx == null) return null
49
+ ctx.imageSmoothingQuality = 'high'
50
+ ctx.drawImage(a, 0, 0, w, h)
51
+ const pa = ctx.getImageData(0, 0, w, h).data
52
+ ctx.clearRect(0, 0, w, h)
53
+ ctx.drawImage(b, 0, 0, w, h)
54
+ const out = ctx.getImageData(0, 0, w, h)
55
+ const pb = out.data
56
+ let changed = 0
57
+ for (let i = 0; i < pb.length; i += 4) {
58
+ const d =
59
+ Math.abs((pa[i] ?? 0) - (pb[i] ?? 0)) +
60
+ Math.abs((pa[i + 1] ?? 0) - (pb[i + 1] ?? 0)) +
61
+ Math.abs((pa[i + 2] ?? 0) - (pb[i + 2] ?? 0))
62
+ if (d > DIFF_NOISE) {
63
+ changed++
64
+ continue
65
+ }
66
+ const v = 228 + ((pb[i] ?? 0) * 0.3 + (pb[i + 1] ?? 0) * 0.59 + (pb[i + 2] ?? 0) * 0.11) * 0.1
67
+ pb[i] = v
68
+ pb[i + 1] = v
69
+ pb[i + 2] = v
70
+ }
71
+ ctx.putImageData(out, 0, 0)
72
+ return { canvas, share: changed / (w * h) }
73
+ } catch (e) {
74
+ console.error('🔴 diff failed:', e)
75
+ return null
76
+ }
77
+ })()
78
+ diffCache.set(key, hit)
79
+ }
80
+ return hit
81
+ }
82
+
83
+ /** the diff canvas on the box: one canvas per pair, mounted where the view puts it */
84
+ function DiffLayer(p: { diff: Diff; box: Box }) {
85
+ const ref = useRef<HTMLDivElement>(null)
86
+ useLayoutEffect(() => {
87
+ const el = ref.current
88
+ if (el == null) return
89
+ const c = p.diff.canvas
90
+ if (c.parentElement !== el) el.replaceChildren(c)
91
+ c.className = `layer ${p.box.z > 1.01 ? 'px' : ''}`
92
+ Object.assign(c.style, {
93
+ left: `${p.box.left}px`,
94
+ top: `${p.box.top}px`,
95
+ width: `${p.box.width}px`,
96
+ height: `${p.box.height}px`,
97
+ })
98
+ })
99
+ return <div ref={ref} className="fill" />
100
+ }
101
+
102
+ const Tag = (p: { side: 'before' | 'after'; name: string }) => <span className={`sidetag ${p.side}`}>{p.name}</span>
103
+
104
+ const Stage = observer(function Stage(p: { st: AppSt; before: string; after: string }) {
105
+ const { st } = p
106
+ const [peek, setPeek] = useState(false)
107
+ const [diff, setDiff] = useState<Diff | null | undefined>(undefined)
108
+ const bName = st.nameOf(st.before)
109
+ const aName = st.after != null ? st.nameOf(st.after) : ''
110
+
111
+ useEffect(() => {
112
+ if (st.mode !== 'diff') return
113
+ let live = true
114
+ setDiff(undefined)
115
+ void diffOf(p.before, p.after, st.outW, st.outH).then((d) => live && setDiff(d))
116
+ return () => {
117
+ live = false
118
+ }
119
+ }, [st.mode, p.before, p.after, st.outW, st.outH])
120
+
121
+ if (st.mode === 'side')
122
+ return (
123
+ <div className="stage side">
124
+ <div className="cell">
125
+ <Viewport st={st} className="side-before">
126
+ {(box) => <Layer url={p.before} box={box} alt={bName} />}
127
+ </Viewport>
128
+ <Tag side="before" name={bName} />
129
+ </div>
130
+ <div className="cell">
131
+ <Viewport st={st} className="side-after">
132
+ {(box) => <Layer url={p.after} box={box} alt={aName} />}
133
+ </Viewport>
134
+ <Tag side="after" name={aName} />
135
+ </div>
136
+ </div>
137
+ )
138
+ if (st.mode === 'diff')
139
+ return (
140
+ <div className="stage">
141
+ <div className="cell">
142
+ <Viewport st={st}>{(box) => (diff != null ? <DiffLayer diff={diff} box={box} /> : null)}</Viewport>
143
+ <Tag side="after" name={aName} />
144
+ </div>
145
+ <div className="caption">
146
+ changes view: only the changed pixels are coloured, <b>{changesWords(diff === undefined ? undefined : (diff?.share ?? null))}</b> · ◫ or D for the normal view
147
+ </div>
148
+ </div>
149
+ )
150
+ if (st.mode === 'mod')
151
+ return (
152
+ <div className="stage">
153
+ <div className="cell">
154
+ <Viewport st={st} className={peek ? 'side-before' : 'side-after'} onHover={setPeek}>
155
+ {(box) => <Layer url={peek ? p.before : p.after} box={box} />}
156
+ </Viewport>
157
+ <Tag side={peek ? 'before' : 'after'} name={peek ? bName : aName} />
158
+ </div>
159
+ <div className="caption">the after alone; the pointer over the image shows the before</div>
160
+ </div>
161
+ )
162
+ const pct = st.split * 100
163
+ // the curtain: a press within 12 px of the line drags the line, anywhere else pans
164
+ const press = (e: React.PointerEvent<HTMLDivElement>, frame: DOMRect): boolean => {
165
+ if (st.mode !== 'swipe' || Math.abs(e.clientX - frame.left - st.split * frame.width) > 12) return false
166
+ e.preventDefault()
167
+ const move = (m: PointerEvent): void => st.set('split', Math.min(1, Math.max(0, (m.clientX - frame.left) / frame.width)))
168
+ const up = (): void => {
169
+ window.removeEventListener('pointermove', move)
170
+ window.removeEventListener('pointerup', up)
171
+ }
172
+ window.addEventListener('pointermove', move)
173
+ window.addEventListener('pointerup', up)
174
+ return true
175
+ }
176
+ return (
177
+ <div className="stage">
178
+ <div className="cell">
179
+ <Viewport st={st} onPress={press}>
180
+ {(box) => (
181
+ <>
182
+ <div className="fill" style={st.mode === 'swipe' ? { clipPath: `inset(0 ${100 - pct}% 0 0)` } : undefined}>
183
+ <Layer url={p.before} box={box} />
184
+ </div>
185
+ <div
186
+ className="fill"
187
+ style={st.mode === 'swipe' ? { clipPath: `inset(0 0 0 ${pct}%)` } : { opacity: st.opacity }}
188
+ >
189
+ <Layer url={p.after} box={box} />
190
+ </div>
191
+ {st.mode === 'swipe' && <div className="curtain" style={{ left: `${pct}%` }} />}
192
+ </>
193
+ )}
194
+ </Viewport>
195
+ {st.mode === 'swipe' ? (
196
+ <>
197
+ <span className="sidetag before left">{bName}</span>
198
+ <span className="sidetag after">{aName}</span>
199
+ </>
200
+ ) : (
201
+ <Tag side="after" name={`${aName} over ${bName}`} />
202
+ )}
203
+ </div>
204
+ <div className="caption">
205
+ {st.mode === 'swipe' ? 'curtain: drag the line; a drag anywhere else pans' : `onion skin: the after at ${Math.round(st.opacity * 100)} %`}
206
+ </div>
207
+ </div>
208
+ )
209
+ })
210
+
211
+ /** the pair view over the page: pick the two sides, the mode, the zoom */
212
+ export const Pair = observer(function Pair(p: { st: AppSt }) {
213
+ const { st } = p
214
+ const after = st.after
215
+ if (after == null) return null
216
+ const afterUrl = st.urlOf(after)
217
+ const beforeUrl = st.urlOf(st.before)
218
+ const r = st.result(after)
219
+ const sides = ['source', ...st.done.map((m) => m.id)]
220
+ const pick = (value: string, set: (v: string) => void, title: string) => (
221
+ <select value={value} title={title} onChange={(e) => set(e.target.value)}>
222
+ {sides.map((id) => (
223
+ <option key={id} value={id}>
224
+ {st.nameOf(id)}
225
+ </option>
226
+ ))}
227
+ </select>
228
+ )
229
+ return (
230
+ <div className="pair">
231
+ <div className="pairBar">
232
+ {pick(st.before, (v) => st.set('before', v), 'the before')}
233
+ <button title="swap the two sides" onClick={() => st.swapPair()}>
234
+ ⇄
235
+ </button>
236
+ {pick(after, (v) => st.set('after', v), 'the after')}
237
+ <span className="modes">
238
+ <span className="seg">
239
+ {COMPARE_MODES.map((m) => {
240
+ const o = MODES.find((x) => x.mode === m)
241
+ return (
242
+ <button key={m} title={`${o?.tip ?? m} (D cycles, ⇧D back)`} className={st.mode === m ? 'on' : ''} onClick={() => st.setMode(m)}>
243
+ {o?.glyph ?? m}
244
+ </button>
245
+ )
246
+ })}
247
+ </span>
248
+ <kbd>D</kbd>
249
+ {st.mode === 'onion' && (
250
+ <input
251
+ type="range"
252
+ min={0}
253
+ max={1}
254
+ step={0.05}
255
+ value={st.opacity}
256
+ title={`after ${Math.round(st.opacity * 100)} %`}
257
+ onChange={(e) => st.set('opacity', Number(e.currentTarget.value))}
258
+ />
259
+ )}
260
+ </span>
261
+ <ZoomBar st={st} />
262
+ <span className="dim meta">
263
+ {r?.status === 'done' ? `${timeOf(r)} · ${r.width}×${r.height}` : ''}
264
+ </span>
265
+ {afterUrl != null && (
266
+ <a className="ghost" href={afterUrl} download={`${st.source?.name.replace(/\.\w+$/, '') ?? 'image'}.${after}.x${st.scale}.png`}>
267
+ download
268
+ </a>
269
+ )}
270
+ <button className="ghost" title="close (Esc)" onClick={() => st.closePair()}>
271
+ close
272
+ </button>
273
+ </div>
274
+ {afterUrl != null && beforeUrl != null ? (
275
+ <Stage st={st} before={beforeUrl} after={afterUrl} />
276
+ ) : (
277
+ <div className="err">this side has no finished result yet</div>
278
+ )}
279
+ <div className="dim small keys">
280
+ wheel or pinch: zoom at the pointer · drag: pan · double click: 100 % there, or the whole image · + − 0 (fit) 1 (100 %) · D cycles the modes · Esc
281
+ closes
282
+ </div>
283
+ </div>
284
+ )
285
+ })
@@ -0,0 +1,15 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>upscale explorer</title>
7
+ <meta name="shot-ready" content="wait" />
8
+ <link rel="stylesheet" href="../../explorer-kit/web/base.css" />
9
+ <link rel="stylesheet" href="./styles.css" />
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ <script type="module" src="./main.tsx"></script>
14
+ </body>
15
+ </html>
@@ -0,0 +1,12 @@
1
+ import { createRoot } from 'react-dom/client'
2
+ import { App } from './App.tsx'
3
+ import { AppSt } from './state.ts'
4
+
5
+ const st = new AppSt()
6
+ // console debugging path (app-state-tree: expose the root)
7
+ ;(globalThis as { st?: AppSt }).st = st
8
+ void st.boot()
9
+
10
+ const rootEl = document.getElementById('root')
11
+ if (rootEl == null) throw new Error('#root missing from index.html')
12
+ createRoot(rootEl).render(<App st={st} />)
@@ -0,0 +1,279 @@
1
+ // the one state tree of the page: the catalog, the source image, one result per (image, scale,
2
+ // model), and ONE view (centre and zoom) shared by every picture that shows a result: the loupe's
3
+ // tiles and both sides of a compared pair show the same crop at the same zoom.
4
+ import { makeAutoObservable, runInAction } from 'mobx'
5
+ import {
6
+ fetchCatalog,
7
+ RunQueue,
8
+ sampleBlob,
9
+ uploadSource,
10
+ type CardInfo,
11
+ type RunSt,
12
+ type Source,
13
+ } from '../../explorer-kit/web/runs.ts'
14
+
15
+ export type ModelInfo = CardInfo & {
16
+ kind: 'baseline' | 'model' | 'diffusion'
17
+ tier: 'modern' | 'classic'
18
+ arch: string
19
+ native: number
20
+ license: string
21
+ }
22
+ export type Scale = 2 | 4
23
+ export type Layout = 'grid' | 'loupe'
24
+ export type CompareMode = 'side' | 'swipe' | 'onion' | 'mod' | 'diff'
25
+ export const COMPARE_MODES: readonly CompareMode[] = ['side', 'swipe', 'onion', 'mod', 'diff']
26
+ /** what a pair compares against when nothing else is picked: the source enlarged with no model */
27
+ export const BASELINE = 'lanczos'
28
+ /** the source as the browser scales it, before the Lanczos result is in */
29
+ export const SOURCE = 'source'
30
+
31
+ /** the centre of the view, 0..1 over the image, and its zoom: device pixels per image pixel
32
+ * (1 = 100 %, each pixel of the result on one pixel of the screen); 'fit' = the whole image */
33
+ export type View = { cx: number; cy: number; z: number | 'fit' }
34
+
35
+ const clamp = (v: number, a: number, b: number): number => Math.min(b, Math.max(a, v))
36
+ export const Z_MIN = 0.05
37
+ export const Z_MAX = 16
38
+
39
+ export class AppSt {
40
+ host = ''
41
+ models: ModelInfo[] = []
42
+ samples: string[] = []
43
+ loadError: string | null = null
44
+ source: Source | null = null
45
+ scale: Scale = 4
46
+ showClassic = false
47
+ showMissing = true
48
+ layout: Layout = 'grid'
49
+ view: View = { cx: 0.5, cy: 0.5, z: 1 }
50
+ /** the loupe's tile edge, css px */
51
+ tile = 360
52
+ /** the compared pair: `after` set = the compare view is open */
53
+ before = BASELINE
54
+ after: string | null = null
55
+ mode: CompareMode = 'side'
56
+ opacity = 0.5
57
+ split = 0.5
58
+ runs = new RunQueue()
59
+ /** a small picture of each finished result, for the grid: result key → object url */
60
+ thumbs = new Map<string, string>()
61
+
62
+ constructor() {
63
+ makeAutoObservable<this, 'thumbing'>(this, { thumbs: true, thumbing: false })
64
+ }
65
+
66
+ async boot(): Promise<void> {
67
+ try {
68
+ const c = await fetchCatalog<ModelInfo>()
69
+ runInAction(() => {
70
+ this.host = c.host
71
+ this.models = c.models
72
+ this.samples = c.samples
73
+ })
74
+ // deep link: ?image=<sample>&scale=2|4&classic=1&run=all|<id,id>&layout=loupe&at=<cx>,<cy>&z=<zoom|fit>
75
+ // &compare=<after>&before=<id>&mode=side|swipe|onion|mod|diff
76
+ const q = new URLSearchParams(location.search)
77
+ if (q.get('scale') === '2') this.set('scale', 2)
78
+ if (q.get('classic') === '1') this.set('showClassic', true)
79
+ const pick = q.get('image')
80
+ const first = (pick != null && c.samples.includes(pick) ? pick : null) ?? c.samples[0]
81
+ if (first != null) await this.loadSample(first)
82
+ const run = q.get('run')
83
+ if (run === 'all') this.runAll()
84
+ else if (run != null) for (const id of run.split(',')) if (this.model(id)?.ok === true) this.enqueue(id)
85
+ const at = q.get('at')?.split(',').map(Number)
86
+ const z = q.get('z')
87
+ this.setView({
88
+ cx: at?.[0] ?? this.view.cx,
89
+ cy: at?.[1] ?? this.view.cy,
90
+ z: z === 'fit' ? 'fit' : z != null ? Number(z) : this.view.z,
91
+ })
92
+ if (q.get('layout') === 'loupe') this.set('layout', 'loupe')
93
+ const mode = COMPARE_MODES.find((m) => m === q.get('mode'))
94
+ if (mode != null) this.setMode(mode)
95
+ await this.settled()
96
+ const after = q.get('compare')
97
+ if (after != null) this.openPair(after, q.get('before') ?? undefined, z == null)
98
+ } catch (e) {
99
+ runInAction(() => (this.loadError = e instanceof Error ? e.message : String(e)))
100
+ }
101
+ // the shot service waits for this mark (sk shot): every queued run has ended
102
+ document.querySelector('meta[name="shot-ready"]')?.setAttribute('content', 'ready')
103
+ }
104
+
105
+ get visibleModels(): ModelInfo[] {
106
+ return this.models.filter((m) => (this.showClassic || m.tier === 'modern') && (this.showMissing || m.ok))
107
+ }
108
+ get runnable(): ModelInfo[] {
109
+ return this.visibleModels.filter((m) => m.ok)
110
+ }
111
+ get busy(): boolean {
112
+ return this.runs.busy
113
+ }
114
+ model(id: string): ModelInfo | undefined {
115
+ return this.models.find((m) => m.id === id)
116
+ }
117
+ resultKey(model: string): string {
118
+ return `${this.source?.key ?? '-'}:${this.scale}:${model}`
119
+ }
120
+ result(model: string): RunSt | undefined {
121
+ return this.runs.get(this.resultKey(model))
122
+ }
123
+ /** the finished results of the visible models, in catalog order */
124
+ get done(): ModelInfo[] {
125
+ return this.visibleModels.filter((m) => this.result(m.id)?.status === 'done')
126
+ }
127
+ /** every pixel size the results share: the source times the scale */
128
+ get outW(): number {
129
+ return (this.source?.width ?? 0) * this.scale
130
+ }
131
+ get outH(): number {
132
+ return (this.source?.height ?? 0) * this.scale
133
+ }
134
+ /** the picture of a compare side: a result, or the source scaled by the browser */
135
+ urlOf(id: string): string | null {
136
+ if (id === SOURCE) return this.source?.url ?? null
137
+ const r = this.result(id)
138
+ return r?.status === 'done' ? r.url : null
139
+ }
140
+ nameOf(id: string): string {
141
+ if (id === SOURCE) return 'source (browser scaled)'
142
+ const m = this.model(id)
143
+ return m == null ? id : `${m.label} ${m.family}`
144
+ }
145
+
146
+ async loadSample(name: string): Promise<void> {
147
+ await this.setSource(await sampleBlob(name), name)
148
+ }
149
+
150
+ async setSource(blob: Blob, name: string): Promise<void> {
151
+ const source = await uploadSource(blob, name)
152
+ runInAction(() => {
153
+ this.source = source
154
+ this.after = null
155
+ })
156
+ }
157
+
158
+ enqueue(model: string): void {
159
+ const src = this.source
160
+ if (src == null) return
161
+ const key = this.resultKey(model)
162
+ this.runs.enqueue(key, { image: src.key, model, scale: this.scale }, () => {
163
+ this.thumbing.push(this.makeThumb(key))
164
+ })
165
+ }
166
+
167
+ runAll(): void {
168
+ for (const m of this.runnable) if (this.result(m.id)?.status !== 'done') this.enqueue(m.id)
169
+ }
170
+
171
+ /** every queued run ended and its thumbnail is drawn */
172
+ async settled(): Promise<void> {
173
+ await this.runs.settled()
174
+ await Promise.all(this.thumbing)
175
+ }
176
+ private thumbing: Promise<void>[] = []
177
+
178
+ /** a 640 px wide copy of a finished result: the grid shows 20 of them at once, never the 12 MP files */
179
+ private async makeThumb(key: string): Promise<void> {
180
+ const r = this.runs.get(key)
181
+ if (r?.url == null || this.thumbs.has(key)) return
182
+ const blob = await (await fetch(r.url)).blob()
183
+ const bmp = await createImageBitmap(blob, { resizeWidth: 640, resizeQuality: 'high' })
184
+ const c = document.createElement('canvas')
185
+ c.width = bmp.width
186
+ c.height = bmp.height
187
+ c.getContext('2d')?.drawImage(bmp, 0, 0)
188
+ const small = await new Promise<Blob | null>((ok) => c.toBlob(ok, 'image/webp', 0.9))
189
+ if (small != null) runInAction(() => this.thumbs.set(key, URL.createObjectURL(small)))
190
+ }
191
+ thumb(model: string): string | null {
192
+ return this.thumbs.get(this.resultKey(model)) ?? null
193
+ }
194
+
195
+ // ── the shared view ──
196
+ setView(v: View): void {
197
+ this.view = v.z === 'fit' ? v : { cx: clamp(v.cx, 0, 1), cy: clamp(v.cy, 0, 1), z: clamp(v.z, Z_MIN, Z_MAX) }
198
+ }
199
+ /** the zoom a frame of `fw` × `fh` css px shows, as device pixels per image pixel */
200
+ zoomIn(fw: number, fh: number): number {
201
+ if (this.view.z !== 'fit') return this.view.z
202
+ if (this.outW === 0) return 1
203
+ return Math.min(fw / this.outW, fh / this.outH) * devicePixelRatio
204
+ }
205
+ /** zoom by `k` around the point (px, py) of a frame of fw × fh css px: that pixel stays put */
206
+ zoomAt(k: number, px: number, py: number, fw: number, fh: number): void {
207
+ const z = this.zoomIn(fw, fh)
208
+ const s = z / devicePixelRatio
209
+ const W = this.outW
210
+ const H = this.outH
211
+ const cx = this.view.z === 'fit' ? 0.5 : this.view.cx
212
+ const cy = this.view.z === 'fit' ? 0.5 : this.view.cy
213
+ const u = cx + (px - fw / 2) / (W * s)
214
+ const v = cy + (py - fh / 2) / (H * s)
215
+ const z2 = clamp(z * k, Z_MIN, Z_MAX)
216
+ const s2 = z2 / devicePixelRatio
217
+ this.setView({ cx: u - (px - fw / 2) / (W * s2), cy: v - (py - fh / 2) / (H * s2), z: z2 })
218
+ }
219
+ /** move the view by a drag of dx, dy css px */
220
+ pan(dx: number, dy: number, fw: number, fh: number): void {
221
+ const s = this.zoomIn(fw, fh) / devicePixelRatio
222
+ const cx = this.view.z === 'fit' ? 0.5 : this.view.cx
223
+ const cy = this.view.z === 'fit' ? 0.5 : this.view.cy
224
+ this.setView({ cx: cx - dx / (this.outW * s), cy: cy - dy / (this.outH * s), z: this.zoomIn(fw, fh) })
225
+ }
226
+ /** the last frame a viewport measured, css px: + and − from 'fit' start at its fit zoom */
227
+ frame = { w: 0, h: 0 }
228
+ noteFrame(w: number, h: number): void {
229
+ this.frame = { w, h }
230
+ }
231
+ /** + / − keys and buttons: around the centre */
232
+ step(k: number): void {
233
+ const z = this.zoomIn(this.frame.w, this.frame.h)
234
+ const centred = this.view.z === 'fit' ? { cx: 0.5, cy: 0.5 } : this.view
235
+ this.setView({ ...centred, z: z * k })
236
+ }
237
+ fit(): void {
238
+ this.setView({ cx: 0.5, cy: 0.5, z: 'fit' })
239
+ }
240
+ actual(): void {
241
+ const centred = this.view.z === 'fit' ? { cx: 0.5, cy: 0.5 } : this.view
242
+ this.setView({ ...centred, z: 1 })
243
+ }
244
+
245
+ // ── the compared pair ──
246
+ /** open the pair view on `after`, against `before` (else the Lanczos baseline, else the source);
247
+ * `at`: the point of the image the click landed on, which the view centres at 100 % */
248
+ openPair(after: string, before?: string, fit = false, at?: { u: number; v: number }): void {
249
+ this.after = after
250
+ const fallback = this.urlOf(BASELINE) != null && after !== BASELINE ? BASELINE : SOURCE
251
+ this.before = before != null && this.urlOf(before) != null ? before : fallback
252
+ if (at != null) this.setView({ cx: at.u, cy: at.v, z: 1 })
253
+ else if (fit) this.fit()
254
+ }
255
+ closePair(): void {
256
+ this.after = null
257
+ }
258
+ setMode(m: CompareMode): void {
259
+ this.mode = m
260
+ }
261
+ /** D cycles the modes, ⇧D goes back */
262
+ cycleMode(step: 1 | -1): void {
263
+ const i = COMPARE_MODES.indexOf(this.mode)
264
+ this.mode = COMPARE_MODES[(i + step + COMPARE_MODES.length) % COMPARE_MODES.length] ?? 'side'
265
+ }
266
+ swapPair(): void {
267
+ if (this.after == null) return
268
+ const a = this.after
269
+ this.after = this.before
270
+ this.before = a
271
+ }
272
+
273
+ set<K extends 'scale' | 'showClassic' | 'showMissing' | 'layout' | 'tile' | 'before' | 'after' | 'opacity' | 'split'>(
274
+ k: K,
275
+ v: this[K],
276
+ ): void {
277
+ this[k] = v
278
+ }
279
+ }