File size: 20,003 Bytes
932a7fd
241036e
932a7fd
974da47
932a7fd
 
c51d86a
61bb967
b022cb9
932a7fd
421fbba
 
3b81d2d
 
421fbba
932a7fd
 
 
 
c20780a
1c1e6e9
 
 
 
2f9a87c
1c1e6e9
 
932a7fd
c32ec0d
f5d8038
c32ec0d
f5d8038
797cbb8
cb3fdda
8c5d17c
dbc8f44
f4dea7d
932a7fd
 
 
1c1e6e9
 
 
 
 
2f9a87c
1c1e6e9
 
 
f5d8038
 
 
932a7fd
 
 
 
f658021
c32ec0d
3b81d2d
cb3fdda
c32ec0d
f309083
8c5d17c
2f9a87c
f4dea7d
f5d8038
932a7fd
2f9a87c
 
 
 
 
 
 
 
 
797cbb8
53fde26
421fbba
 
 
3b81d2d
 
421fbba
 
 
 
 
 
 
c20780a
932a7fd
b022cb9
 
 
 
11443d4
b022cb9
1c1e6e9
c20780a
1c1e6e9
 
 
b022cb9
2f9a87c
1c1e6e9
 
 
932a7fd
c32ec0d
f5d8038
 
b022cb9
2f9a87c
 
c51d86a
2f9a87c
 
 
b022cb9
2f9a87c
 
dbc8f44
2f9a87c
f4dea7d
932a7fd
 
 
1c1e6e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f9a87c
 
 
 
 
 
 
 
 
1c1e6e9
2f9a87c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c1e6e9
 
 
 
a296341
1c1e6e9
 
a296341
 
2f9a87c
 
 
 
 
1c1e6e9
2f9a87c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a296341
2f9a87c
 
 
 
 
 
 
 
1c1e6e9
a296341
 
1c1e6e9
a296341
1c1e6e9
a296341
 
1c1e6e9
f5d8038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241036e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb3fdda
 
932a7fd
f658021
 
 
 
 
 
 
 
c32ec0d
241036e
c32ec0d
 
 
 
 
 
241036e
 
f309083
 
 
 
 
 
 
 
3b81d2d
 
5dd2af5
2f9a87c
3b81d2d
 
 
 
 
 
 
 
 
5dd2af5
797cbb8
 
2f9a87c
 
 
 
 
 
 
 
 
 
 
 
 
 
5dd2af5
2f9a87c
797cbb8
 
cb3fdda
8c5d17c
f4dea7d
f5d8038
 
932a7fd
 
 
 
 
 
 
 
 
 
 
 
2f9a87c
 
 
 
 
 
 
 
 
 
b6caea7
dbc8f44
b6caea7
dbc8f44
c32ec0d
dbc8f44
1c1e6e9
dbc8f44
1c1e6e9
b6caea7
 
 
 
 
 
dbc8f44
 
 
 
 
 
 
 
 
 
 
797cbb8
2f9a87c
797cbb8
2f9a87c
5dd2af5
 
2f9a87c
5dd2af5
 
 
2f9a87c
5dd2af5
 
797cbb8
2f9a87c
 
 
 
797cbb8
c32ec0d
2f9a87c
 
 
 
 
 
 
 
797cbb8
 
 
2f9a87c
5dd2af5
797cbb8
c20780a
421fbba
53fde26
c20780a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
974da47
c20780a
 
 
 
 
 
 
 
 
 
 
 
53fde26
 
 
c20780a
 
 
 
 
 
974da47
c20780a
974da47
53fde26
974da47
c20780a
 
 
 
 
 
974da47
c20780a
 
 
974da47
 
c20780a
 
 
 
 
 
974da47
c20780a
974da47
 
c20780a
 
 
 
 
 
 
974da47
53fde26
974da47
 
c20780a
 
 
 
 
 
 
 
 
 
421fbba
 
 
3b81d2d
 
421fbba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
974da47
421fbba
 
 
 
 
 
 
974da47
421fbba
 
 
 
 
974da47
421fbba
 
 
 
 
 
 
 
 
 
 
 
5e08719
421fbba
 
5e08719
421fbba
 
 
 
 
5e08719
421fbba
 
 
 
 
 
 
 
5e08719
421fbba
 
3b81d2d
 
421fbba
 
3b81d2d
 
421fbba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b81d2d
 
421fbba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b81d2d
 
421fbba
 
 
 
 
 
 
 
 
 
c20780a
421fbba
c20780a
53fde26
c20780a
 
 
 
 
 
 
 
 
 
 
 
421fbba
 
974da47
9ee3c2f
9c58e18
974da47
9ee3c2f
974da47
421fbba
974da47
c20780a
 
 
 
 
 
 
421fbba
932a7fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
"use client"

import { create } from "zustand"
import { ClapProject, ClapMediaOrientation, ClapSegment, ClapSegmentCategory, ClapSegmentStatus, ClapOutputType, ClapSegmentFilteringMode, filterSegments, newClap, newSegment, parseClap, serializeClap } from "@aitube/clap"

import { FontName } from "@/lib/fonts"
import { Preset, PresetName, defaultPreset, getPreset, getRandomPreset } from "@/app/engine/presets"
import { RenderedScene } from "@/types"
import { getParam } from "@/lib/getParam"

import { LayoutName, defaultLayout, getRandomLayoutName } from "../layouts"
import { putTextInInput } from "@/lib/putTextInInput"
import { parsePresetFromPrompts } from "@/lib/parsePresetFromPrompts"
import { parseLayoutFromStoryboards } from "@/lib/parseLayoutFromStoryboards"

export const useStore = create<{
  prompt: string
  font: FontName
  preset: Preset
  currentClap?: ClapProject
  currentNbPanelsPerPage: number
  maxNbPanelsPerPage: number
  currentNbPages: number
  maxNbPages: number
  previousNbPanels: number
  currentNbPanels: number
  maxNbPanels: number
  panels: string[]
  captions: string[]
  upscaleQueue: Record<string, RenderedScene>
  showCaptions: boolean
  renderedScenes: Record<string, RenderedScene>
  layout: LayoutName
  layouts: LayoutName[]
  zoomLevel: number
  page: HTMLDivElement
  isGeneratingStory: boolean
  panelGenerationStatus: Record<number, boolean>
  isGeneratingText: boolean
  atLeastOnePanelIsBusy: boolean

  setCurrentNbPanelsPerPage: (currentNbPanelsPerPage: number) => void
  setMaxNbPanelsPerPage: (maxNbPanelsPerPage: number) => void
  setCurrentNbPages: (currentNbPages: number) => void
  setMaxNbPages: (maxNbPages: number) => void
  setPreviousNbPanels: (previousNbPanels: number) => void
  setCurrentNbPanels: (currentNbPanels: number) => void
  setMaxNbPanels: (maxNbPanels: number) => void
  
  setRendered: (panelId: string, renderedScene: RenderedScene) => void
  addToUpscaleQueue: (panelId: string, renderedScene: RenderedScene) => void
  removeFromUpscaleQueue: (panelId: string) => void
  setPrompt: (prompt: string) => void
  setFont: (font: FontName) => void
  setPreset: (preset: Preset) => void
  setPanels: (panels: string[]) => void
  setPanelPrompt: (newPrompt: string, index: number) => void
  setShowCaptions: (showCaptions: boolean) => void
  setLayout: (layout: LayoutName, index?: number) => void
  setLayouts: (layouts: LayoutName[]) => void
  setCaptions: (captions: string[]) => void
  setPanelCaption: (newCaption: string, index: number) => void
  setZoomLevel: (zoomLevel: number) => void

  setGeneratingStory: (isGeneratingStory: boolean) => void
  setGeneratingImages: (panelId: string, value: boolean) => void
  setGeneratingText: (isGeneratingText: boolean) => void
  
  // I think we should deprecate those three functions
  // this was used to keep track of the page HTML element,
  // for use with a HTML-to-bitmap library
  // but the CSS layout wasn't followed properly and it depended on the zoom level
  // pageToImage: () => Promise<string>
  // download: () => Promise<void>
  // setPage: (page: HTMLDivElement) => void

  generate: (prompt: string, presetName: PresetName, layoutName: LayoutName) => void
  convertComicToClap: () => Promise<ClapProject>
  convertClapToComic: (clap: ClapProject) => Promise<{
    currentNbPanels: number
    prompt: string
    preset: Preset
    layout: LayoutName
    storyPrompt: string
    stylePrompt: string
    panels: string[]
    renderedScenes: Record<string, RenderedScene>
    captions: string[]
  }>
  loadClap: (blob: Blob) => Promise<void>
  downloadClap: () => Promise<void>
}>((set, get) => ({
  prompt:
    (getParam("stylePrompt", "") || getParam("storyPrompt", ""))
     ? `${getParam("stylePrompt", "")}||${getParam("storyPrompt", "")}`
     : "",
  font: "actionman",
  preset: getPreset(getParam("preset", defaultPreset)),

  currentClap: undefined,
  currentNbPanelsPerPage: 4,
  maxNbPanelsPerPage: 4,
  currentNbPages: 1,
  maxNbPages: getParam("maxNbPages", 1),
  previousNbPanels: 0,
  currentNbPanels: 4,
  maxNbPanels: 4,

  panels: [],
  captions: [],
  upscaleQueue: {} as Record<string, RenderedScene>,
  renderedScenes: {} as Record<string, RenderedScene>,
  showCaptions: getParam("showCaptions", false),

  // deprecated?
  layout: defaultLayout,

  layouts: [defaultLayout, defaultLayout, defaultLayout, defaultLayout],

  zoomLevel: getParam("zoomLevel", 60),

  // deprecated?
  page: undefined as unknown as HTMLDivElement,

  isGeneratingStory: false,
  panelGenerationStatus: {},
  isGeneratingText: false,
  atLeastOnePanelIsBusy: false,

  setCurrentNbPanelsPerPage: (currentNbPanelsPerPage: number) => {
    const { currentNbPages } = get()
    set({
      currentNbPanelsPerPage,
      currentNbPanels: currentNbPanelsPerPage * currentNbPages
    })
  },
  setMaxNbPanelsPerPage: (maxNbPanelsPerPage: number) => {
    const { maxNbPages } = get()
    set({
      maxNbPanelsPerPage,
      maxNbPanels: maxNbPanelsPerPage * maxNbPages,
    })
  },
  setCurrentNbPages: (currentNbPages: number) => {
    const state = get()

    const newCurrentNumberOfPages = Math.min(state.maxNbPages, currentNbPages)
    
    const newCurrentNbPanels = state.currentNbPanelsPerPage * newCurrentNumberOfPages

    /*
    console.log(`setCurrentNbPages(${currentNbPages}): ${JSON.stringify({
      "state.maxNbPages": state.maxNbPages,
      currentNbPages,
      newCurrentNumberOfPages,
      "state.currentNbPanelsPerPage": state.currentNbPanelsPerPage,
      newCurrentNbPanels,
      "state.currentNbPanels": state.currentNbPanels,
      "state.previousNbPanels": state.previousNbPanels,
      previousNbPanels:
      newCurrentNbPanels > state.currentNbPanels ? state.currentNbPanels :
      newCurrentNbPanels < state.currentNbPanels ? 0 :
      state.previousNbPanels,

    }, null, 2)}`)
    */

    set({
      // we keep the previous number of panels for convenience
      // so if we are adding a new panel,
      // state.currentNbPanels gets copied to state.previousNbPanels
      previousNbPanels:
        newCurrentNbPanels > state.currentNbPanels ? state.currentNbPanels :
        newCurrentNbPanels < state.currentNbPanels ? 0 :
        state.previousNbPanels,

      currentNbPanels: newCurrentNbPanels,
      currentNbPages: newCurrentNumberOfPages,
  
    })
  },
  setMaxNbPages: (maxNbPages: number) => {
    const { maxNbPanelsPerPage } = get()
    set({
      maxNbPages,
      maxNbPanels: maxNbPanelsPerPage * maxNbPages,
    })
  },
  setPreviousNbPanels: (previousNbPanels: number) => {
    set({
      previousNbPanels
    })
  },
  setCurrentNbPanels: (currentNbPanels: number) => {
    const state = get()


    /*
    console.log(`setCurrentNbPanels(${currentNbPanels}): ${JSON.stringify({
      "state.maxNbPages": state.maxNbPages,
      "state.currentNbPages": state.currentNbPages,
      currentNbPanels,
      "state.currentNbPanelsPerPage": state.currentNbPanelsPerPage,
      "state.currentNbPanels": state.currentNbPanels,
      "state.previousNbPanels": state.previousNbPanels,
      previousNbPanels:
      currentNbPanels > state.currentNbPanels ? state.currentNbPanels :
        currentNbPanels < state.currentNbPanels ? 0 :
        state.previousNbPanels,

    }, null, 2)}`)
    */

    set({
      // we keep the previous number of panels for convenience
      // so if we are adding a new panel,
      // state.currentNbPanels gets copied to state.previousNbPanels
      previousNbPanels:
        currentNbPanels > state.currentNbPanels ? state.currentNbPanels :
        currentNbPanels < state.currentNbPanels ? 0 :
        state.previousNbPanels,
      
      currentNbPanels,
    })
  },
  setMaxNbPanels: (maxNbPanels: number) => {
    set({
      maxNbPanels
    })
  },
  
  setRendered: (panelId: string, renderedScene: RenderedScene) => {
    const { renderedScenes } = get()
    set({
      renderedScenes: {
        ...renderedScenes,
        [panelId]: renderedScene
      }
    })
  },
  addToUpscaleQueue: (panelId: string, renderedScene: RenderedScene) => {
    const { upscaleQueue } = get()
    set({
      upscaleQueue: {
        ...upscaleQueue,
        [panelId]: renderedScene
      },
    })
  },
  removeFromUpscaleQueue: (panelId: string) => {
    const upscaleQueue = { ...get().upscaleQueue }
    delete upscaleQueue[panelId]
    set({
      upscaleQueue,
    })
  },
  setPrompt: (prompt: string) => {
    const existingPrompt = get().prompt
    if (prompt === existingPrompt) { return }
    set({
      prompt,
    })
  },
  setFont: (font: FontName) => {
    const existingFont = get().font
    if (font === existingFont) { return }
    set({
      font,
    })
  },
  setPreset: (preset: Preset) => {
    const existingPreset = get().preset
    if (preset.label === existingPreset.label) { return }
    set({
      preset,
    })
  },
  setPanels: (panels: string[]) => set({ panels }),
  setPanelPrompt: (newPrompt, index) => {
    const { panels } = get()
    set({
      panels: panels.map((p, i) => (
        index === i ? newPrompt : p
      ))
    })
  },
  setCaptions: (captions: string[]) => {
    set({
      captions,
    })
  },
  setShowCaptions: (showCaptions: boolean) => {
    set({
      showCaptions,
    })
  },
  setPanelCaption: (newCaption, index) => {
    const { captions } = get()
    set({
      captions: captions.map((c, i) => (
        index === i ? newCaption : c
      ))
    })
  },
  setLayout: (layoutName: LayoutName, index?: number) => {
    const { maxNbPages, currentNbPanelsPerPage, layouts } = get()

    for (let i = 0; i < maxNbPages; i++) {
      let name = layoutName === "random" ? getRandomLayoutName() : layoutName

      if (typeof index === "number" && !isNaN(index) && isFinite(index)) {
        if (i === index) {
          layouts[i] = name
        }
      } else {
        layouts[i] = name
      }
    }

    set({
      // changing the layout isn't a free pass to generate tons of panels at once,
      // so we reset pretty much everything
      previousNbPanels: 0,
      currentNbPages: 1,
      currentNbPanels: currentNbPanelsPerPage,
      panels: [],
      captions: [],
      upscaleQueue: {},
      renderedScenes: {},
      isGeneratingStory: false,
      panelGenerationStatus: {},
      isGeneratingText: false,
      atLeastOnePanelIsBusy: false,

      layouts,
      layout: layouts[0],
    })
  },
  setLayouts: (layouts: LayoutName[]) => set({ layouts }),
  setZoomLevel: (zoomLevel: number) =>  set({ zoomLevel }),
  setGeneratingStory: (isGeneratingStory: boolean) => set({ isGeneratingStory }),
  setGeneratingImages: (panelId: string, value: boolean) => {
    const panelGenerationStatus: Record<string, boolean> = {
      ...get().panelGenerationStatus,
      [panelId]: value
    }

    const atLeastOnePanelIsBusy = Object.values(panelGenerationStatus).includes(true)
    
    set({
      panelGenerationStatus,
      atLeastOnePanelIsBusy
    })
  },
  setGeneratingText: (isGeneratingText: boolean) => set({ isGeneratingText }),

  // I think we should deprecate those three functions
  // this was used to keep track of the page HTML element,
  // for use with a HTML-to-bitmap library
  // but the CSS layout wasn't followed properly and it depended on the zoom level
  /*
  setPage: (page: HTMLDivElement) => {
    if (!page) { return }
    set({ page })
  },
  pageToImage: async () => {
    const { page } = get()
    if (!page) { return "" }
    
    
    const canvas = await html2canvas(page)
    // console.log("canvas:", canvas)

    const data = canvas.toDataURL('image/jpeg', 0.97)
    return data
  },
  download: async () => {
    const { pageToImage } = get()
    const data = await pageToImage()
   
    const link = document.createElement('a')

    if (typeof link.download === 'string') {
      link.href = data
      link.download = 'comic.jpg'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      window.open(data)
    }
  },
  */
  generate: (prompt: string, presetName: PresetName, layoutName: LayoutName) => {
    const { maxNbPages, currentNbPanelsPerPage } = get()

    const layouts: LayoutName[] = []
    for (let i = 0; i < maxNbPages; i++) {
      layouts.push(
        layoutName === "random"
          ? getRandomLayoutName()
          : layoutName)
    }

    set({
      // we reset pretty much everything
      previousNbPanels: 0,
      currentNbPages: 1,
      currentNbPanels: currentNbPanelsPerPage,
      panels: [],
      captions: [],
      upscaleQueue: {},
      renderedScenes: {},
      isGeneratingStory: false,
      panelGenerationStatus: {},
      isGeneratingText: false,
      atLeastOnePanelIsBusy: false,

      prompt,
      preset: presetName === "random"
        ? getRandomPreset()
        : getPreset(presetName),
      layout: layouts[0],
      layouts,
    })
  },
  
  convertComicToClap: async (): Promise<ClapProject> => {
    const {
      currentNbPanels,
      prompt,
      panels,
      renderedScenes,
      captions
    } = get()

    const defaultSegmentDurationInMs = 7000

    let currentElapsedTimeInMs = 0


    const clap: ClapProject = newClap({
      meta: {
        title: "Untitled", // we don't need a title actually
        description: prompt,
        prompt: prompt,
        synopsis: "",
        licence: "",
        orientation: ClapMediaOrientation.LANDSCAPE,
        width: 512,
        height: 288,
        isInteractive: false,
        isLoop: false,
        durationInMs: panels.length * defaultSegmentDurationInMs,
        defaultVideoModel: "SDXL",
      }
    })

    for (let i = 0; i < panels.length; i++) {

      const panel = panels[i]

      const caption = captions[i]

      const renderedScene = renderedScenes[`${i}`]

      clap.segments.push(newSegment({
        track: 1,
        startTimeInMs: currentElapsedTimeInMs,
        assetDurationInMs: defaultSegmentDurationInMs,
        category: ClapSegmentCategory.STORYBOARD,
        prompt: panel,
        outputType: ClapOutputType.IMAGE,
        assetUrl: renderedScene?.assetUrl || "",
        status: ClapSegmentStatus.COMPLETED,
      }))
  
      clap.segments.push(newSegment({
        track: 2,
        startTimeInMs: currentElapsedTimeInMs,
        assetDurationInMs: defaultSegmentDurationInMs,
        category: ClapSegmentCategory.INTERFACE,
        prompt: caption,
        // assetUrl: `data:text/plain;base64,${btoa(title)}`,
        assetUrl: caption,
        outputType: ClapOutputType.TEXT,
        status: ClapSegmentStatus.COMPLETED,
      }))
  
      clap.segments.push(newSegment({
        track: 3,
        startTimeInMs: currentElapsedTimeInMs,
        assetDurationInMs: defaultSegmentDurationInMs,
        category: ClapSegmentCategory.DIALOGUE,
        prompt: caption,
        outputType: ClapOutputType.AUDIO,
        status: ClapSegmentStatus.TO_GENERATE,
      }))
  
      // the presence of a camera is mandatory
      clap.segments.push(newSegment({
        track: 4,
        startTimeInMs: currentElapsedTimeInMs,
        assetDurationInMs: defaultSegmentDurationInMs,
        category: ClapSegmentCategory.CAMERA,
        prompt: "movie still",
        outputType: ClapOutputType.TEXT,
        status: ClapSegmentStatus.COMPLETED,
      }))
  
      currentElapsedTimeInMs += defaultSegmentDurationInMs
    }

    set({ currentClap: clap })

    return clap
  },

  convertClapToComic: async (clap: ClapProject): Promise<{
    currentNbPanels: number
    prompt: string
    preset: Preset
    layout: LayoutName
    storyPrompt: string
    stylePrompt: string
    panels: string[]
    renderedScenes: Record<string, RenderedScene>
    captions: string[]
  }> => {

    const prompt = clap.meta.description
    const [stylePrompt, storyPrompt] = prompt.split("||").map(x => x.trim())

    const panels: string[] = []
    const renderedScenes: Record<string, RenderedScene> = {}
    const captions: string[] = []

    const panelGenerationStatus: Record<number, boolean> = {}

    const cameraShots = clap.segments.filter(s => s.category === ClapSegmentCategory.CAMERA)

    const shots = cameraShots.map(cameraShot => ({
      camera: cameraShot,
      storyboard: filterSegments(
        ClapSegmentFilteringMode.START,
        cameraShot,
        clap.segments,
        ClapSegmentCategory.STORYBOARD,
      ).at(0) as (ClapSegment | undefined),
      ui: filterSegments(
        ClapSegmentFilteringMode.START,
        cameraShot,
        clap.segments,
        ClapSegmentCategory.INTERFACE,
      ).at(0) as (ClapSegment | undefined)
    })).filter(item => item.storyboard && item.ui) as {
      camera: ClapSegment
      storyboard: ClapSegment
      ui: ClapSegment
    }[]

    shots.forEach(({ camera, storyboard, ui }, id) => {

      panels.push(storyboard.prompt)

      const renderedScene: RenderedScene = {
        renderId: storyboard?.id || "",
        status: "pending",
        assetUrl: "", 
        alt: storyboard?.prompt || "",
        error: "",
        maskUrl: "",
        segments: []
      }

      if (storyboard?.assetUrl) {
        renderedScene.assetUrl = storyboard.assetUrl
        renderedScene.status = "pregenerated" // <- special trick to indicate that it should not be re-generated
      }

      renderedScenes[id] = renderedScene

      panelGenerationStatus[id] = false
      
      captions.push(ui?.prompt || "")
    })


    return {
      currentNbPanels: shots.length,
      prompt,
      preset: parsePresetFromPrompts(panels),
      layout: await parseLayoutFromStoryboards(shots.map(x => x.storyboard)),
      storyPrompt,
      stylePrompt,
      panels,
      renderedScenes,
      captions,

    }
  },

  loadClap: async (blob: Blob) => {
    const { convertClapToComic, currentNbPanelsPerPage } = get()

    const currentClap = await parseClap(blob)

    const {
      currentNbPanels,
      prompt,
      preset,
      layout,
      storyPrompt,
      stylePrompt,
      panels,
      renderedScenes,
      captions,
    } = await convertClapToComic(currentClap)

    // kids, don't do this in your projects: use state managers instead!
    putTextInInput(document.getElementById("top-menu-input-style-prompt") as HTMLInputElement, stylePrompt)
    putTextInInput(document.getElementById("top-menu-input-story-prompt") as HTMLInputElement, storyPrompt)

    set({
      currentClap,
      currentNbPanels,
      prompt,
      preset,
      // layout,
      panels,
      renderedScenes,
      captions,
      currentNbPages: Math.round(currentNbPanels / currentNbPanelsPerPage),
      upscaleQueue: {},
      isGeneratingStory: false,
      isGeneratingText: false,
    })
  },

  downloadClap: async () => {
    const { convertComicToClap, prompt } = get()

    const currentClap = await convertComicToClap()

    if (!currentClap) { throw new Error(`cannot save a clap.. if there is no clap`) }

    const currentClapBlob: Blob = await serializeClap(currentClap)

    // Create an object URL for the compressed clap blob
    const objectUrl = URL.createObjectURL(currentClapBlob)
  
    // Create an anchor element and force browser download
    const anchor = document.createElement("a")
    anchor.href = objectUrl

    const [stylePrompt, storyPrompt] = prompt.split("||").map(x => x.trim())

    const cleanStylePrompt = (stylePrompt || "").replace(/([^a-z0-9, ]+)/gi, " ")

    const firstPartOfStory = (storyPrompt || "").split(",").shift() || ""
    const cleanStoryPrompt = firstPartOfStory.replace(/([^a-z0-9, ]+)/gi, " ")

    const cleanName = `${cleanStoryPrompt.slice(0, 90)} (${cleanStylePrompt.slice(0, 90) || "default style"})`

    anchor.download = `${cleanName}.clap`

    document.body.appendChild(anchor) // Append to the body (could be removed once clicked)
    anchor.click() // Trigger the download
  
    // Cleanup: revoke the object URL and remove the anchor element
    URL.revokeObjectURL(objectUrl)
    document.body.removeChild(anchor)
  },
}))