File size: 32,327 Bytes
2a261b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
import { useState } from 'react'
import {
  Brush,
  Combine,
  Download,
  Eraser,
  Grid3x3,
  LoaderCircle,
  PenTool,
  RotateCcw,
  Save,
  ScanSearch,
  Sparkles,
  Split,
  Trash2,
  X,
} from 'lucide-react'

import { useStore } from '@/store'
import type { Effect, Search } from '@/types'
import { Button } from '@/components/ui/button'
import { Field, Input, Section, Select, SliderField, SwitchField, Textarea, Tooltip } from '@/components/ui/controls'
import { fontFamilyOf } from '@/fonts'
import { cn } from '@/lib/utils'

const fixed = (digits: number) => (value: number) => value.toFixed(digits)
const percent = (value: number) => `${Math.round(value * 100)}%`

const OFF = 'Off'

const EFFECTS: { value: Effect; label: string }[] = [
  { value: 'none', label: 'Paint' },
  { value: 'embroidery', label: 'Embroidery' },
  { value: 'stencil', label: 'Worn stencil' },
  { value: 'neon', label: 'Neon' },
  { value: 'engraving', label: 'Engraving' },
]

/** A color swatch with its hex code, as the Letters section shows it. */
function ColorField({

  label,

  value,

  onChange,

  disabled,

}: {

  label: string

  value: string

  onChange: (value: string) => void

  disabled?: boolean

}) {
  return (
    <Field label={label}>

      <label

        className={cn(

          'flex h-8 w-24 cursor-pointer items-center gap-2 rounded-md border border-input px-2',

          disabled && 'pointer-events-none opacity-50',

        )}

      >

        <input

          type="color"

          value={value}

          disabled={disabled}

          onChange={(event) => onChange(event.target.value)}

          className="size-5 cursor-pointer appearance-none border-0 bg-transparent p-0 [&::-webkit-color-swatch]:rounded [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0"

        />

        <span className="font-mono text-xs uppercase">{value}</span>

      </label>

    </Field>
  )
}

function Lines() {
  const items = useStore((state) => state.items)
  const active = useStore((state) => state.active)
  const setActive = useStore((state) => state.setActive)
  const setText = useStore((state) => state.setText)
  const setErase = useStore((state) => state.setErase)
  const removeItem = useStore((state) => state.removeItem)
  const clearItems = useStore((state) => state.clearItems)
  const resetShape = useStore((state) => state.resetShape)
  const clearStrokes = useStore((state) => state.clearStrokes)
  const joinItems = useStore((state) => state.joinItems)
  const splitItem = useStore((state) => state.splitItem)
  const clearPath = useStore((state) => state.clearPath)
  const clearWarp = useStore((state) => state.clearWarp)
  const look = useStore((state) => state.look)

  return (
    <Section

      title="Text"

      aside={

        items.length > 0 && (

          <div className="flex items-center gap-1">

            {items.length > 1 && (

              <Tooltip content="Take all the selected lines as one block, as in a speech bubble or a sign: one text with line breaks">

                <Button variant="ghost" size="sm" onClick={() => void joinItems()} className="h-6 px-2 text-muted-foreground">

                  <Combine className="size-3.5" /> Join

                </Button>

              </Tooltip>

            )}

            <Button variant="ghost" size="sm" onClick={clearItems} className="h-6 px-2 text-muted-foreground">

              Clear

            </Button>

          </div>

        )

      }

    >

      {items.length === 0 ? (

        <p className="rounded-md border border-dashed px-3 py-4 text-center text-xs leading-relaxed text-muted-foreground">

          Click the text to replace on the image. Each line you pick gets a number here and a field for its new text.

        </p>

      ) : (

        <ol className="space-y-2">

          {items.map((item, index) => {

            const isActive = item.key === active

            const lines = Math.min(6, Math.max(1, item.text.split('\n').length))

            return (

              <li

                key={item.key}

                onPointerDown={() => setActive(item.key)}

                className={cn(

                  'rounded-md border border-transparent p-1.5 transition-colors',

                  isActive && 'border-chosen/50 bg-chosen/5',

                )}

              >

                <div className="flex items-start gap-2">

                  <span

                    className={cn(

                      'mt-1 flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-bold text-[#06281a]',

                      item.erase ? 'bg-destructive' : 'bg-chosen',

                    )}

                  >

                    {index + 1}

                  </span>

                  <Textarea

                    autoFocus={index === items.length - 1 && !item.text && !item.erase}

                    value={item.text}

                    rows={lines}

                    disabled={item.erase}

                    onChange={(event) => setText(item.key, event.target.value)}

                    placeholder={item.erase ? 'Erased: nothing is written here' : item.recipe.join ? 'One line per line of the block' : 'New text'}

                    style={{ fontFamily: fontFamilyOf(look.font) }}

                    className="min-h-8 resize-none py-1 text-[15px] leading-snug"

                  />

                  <Tooltip content={`Old letters: ${item.shape.color}, ${item.shape.width} × ${item.shape.height} px`}>

                    <span

                      className="mt-1.5 size-5 shrink-0 rounded border"

                      style={{ background: look.ownColor ? item.shape.color : look.color }}

                    />

                  </Tooltip>

                  <Button

                    variant="ghost"

                    size="icon-sm"

                    onClick={() => removeItem(item.key)}

                    aria-label={`Remove line ${index + 1}`}

                  >

                    <X />

                  </Button>

                </div>

                <div className="mt-1 flex flex-wrap items-center gap-1 pl-8">

                  <Tooltip content="Erase the old letters and write nothing in their place">

                    <Button

                      variant={item.erase ? 'destructive' : 'ghost'}

                      size="sm"

                      className="h-6 px-2 text-xs"

                      onClick={() => setErase(item.key, !item.erase)}

                    >

                      <Eraser className="size-3" /> Erase only

                    </Button>

                  </Tooltip>

                  {item.recipe.shape && (

                    <Tooltip content="Put the place for the new text back where the letters gave it">

                      <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => void resetShape(item.key)}>

                        <RotateCcw className="size-3" /> Shape

                      </Button>

                    </Tooltip>

                  )}

                  {item.recipe.paint && (

                    <Tooltip content="Remove the brush strokes of this line">

                      <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => void clearStrokes(item.key)}>

                        <Brush className="size-3" /> Strokes {item.recipe.paint.length}

                      </Button>

                    </Tooltip>

                  )}

                  {item.recipe.path && (

                    <Tooltip content="Write the new text where the old one was again, not along the drawn path">

                      <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => void clearPath(item.key)}>

                        <PenTool className="size-3" /> Path

                      </Button>

                    </Tooltip>

                  )}

                  {item.recipe.warp && (

                    <Tooltip content="Undo the hand warp of the letters">

                      <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => void clearWarp(item.key)}>

                        <Grid3x3 className="size-3" /> Warp

                      </Button>

                    </Tooltip>

                  )}

                  {item.recipe.join && (

                    <Tooltip content="Take the block apart into its lines again">

                      <Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => void splitItem(item.key)}>

                        <Split className="size-3" /> Split {item.recipe.join.length}

                      </Button>

                    </Tooltip>

                  )}

                </div>

              </li>

            )

          })}

        </ol>

      )}

    </Section>
  )
}

const SEARCHES: { value: Search; label: string }[] = [
  { value: 'auto', label: 'Detector when it is here' },
  { value: 'light', label: 'Detector, light' },
  { value: 'full', label: 'Detector, full' },
  { value: 'looks', label: 'By looks alone' },
]

const megabytes = (bytes: number) => `${(bytes / 1e6).toFixed(bytes < 1e8 ? 1 : 0)} MB`

/** How the text is found and read: by looks, or with the neural detector, and its models. */
function Finding() {
  const options = useStore((state) => state.options)
  const search = useStore((state) => state.search)
  const setSearch = useStore((state) => state.setSearch)
  const readOld = useStore((state) => state.readOld)
  const setReadOld = useStore((state) => state.setReadOld)
  const models = useStore((state) => state.models)
  const downloadModels = useStore((state) => state.downloadModels)
  const label = SEARCHES.find((entry) => entry.value === search)?.label ?? SEARCHES[0].label
  const inUse = models?.inUse ?? 'looks'
  const downloading = models?.download.running
  const progress = models && models.download.total ? Math.round((models.download.done / models.download.total) * 100) : 0

  return (
    <Section title="Finding the text" defaultOpen={!options?.models?.ready.light}>

      <Field

        label="Search"

        hint="The detector also finds large, heavy, faint and hand-written lettering, and is not fooled by hair or eyes as often as the search by looks."

      >

        <Select

          value={label}

          onValueChange={(chosen) => void setSearch(SEARCHES.find((entry) => entry.label === chosen)?.value ?? 'auto')}

          options={SEARCHES.map((entry) => entry.label)}

        />

      </Field>

      <p className="text-xs text-muted-foreground">

        Looking now: <b>{inUse === 'looks' ? 'by looks alone' : `with the ${inUse} detector`}</b>

      </p>

      {models && !models.onnx && (

        <p className="text-xs text-amber-500">This host's Python has no onnxruntime: only the search by looks works.</p>

      )}

      {models?.onnx &&

        (['light', 'full'] as const).map((choice) =>

          models.ready[choice] ? null : (

            <div key={choice} className="flex items-center justify-between gap-2 text-xs">

              <span className="text-muted-foreground">

                The {choice} detector is not here ({megabytes(models.missing[choice])})

              </span>

              <Button

                variant="outline"

                size="sm"

                className="h-7"

                disabled={downloading}

                onClick={() => void downloadModels(choice)}

              >

                <Download /> Get it

              </Button>

            </div>

          ),

        )}

      {downloading && (

        <div className="space-y-1 text-xs text-muted-foreground">

          <div className="h-1.5 overflow-hidden rounded bg-muted">

            <div className="h-full bg-primary transition-[width]" style={{ width: `${progress}%` }} />

          </div>

          <span>

            {models?.download.current} · {progress}%

          </span>

        </div>

      )}

      <SwitchField

        label="Start with the old text"

        hint="A new line's text field starts with what its old letters say, read by the detector's reader: correct the gibberish instead of typing it all"

        checked={readOld}

        onChange={setReadOld}

        disabled={!models?.ready.light && !models?.ready.full}

      />

    </Section>
  )
}

/** Looks saved under a name: pick one, save the current look, delete one. */
function Presets() {
  const presets = useStore((state) => state.presets)
  const preset = useStore((state) => state.preset)
  const applyPreset = useStore((state) => state.applyPreset)
  const savePreset = useStore((state) => state.savePreset)
  const deletePreset = useStore((state) => state.deletePreset)
  const [naming, setNaming] = useState<string | null>(null)
  const names = Object.keys(presets)

  if (naming !== null) {
    const done = () => {
      void savePreset(naming)
      setNaming(null)
    }
    return (
      <div className="flex gap-2">

        <Input

          autoFocus

          value={naming}

          placeholder="A name for this look"

          onChange={(event) => setNaming(event.target.value)}

          onKeyDown={(event) => {

            if (event.key === 'Enter') done()

            if (event.key === 'Escape') setNaming(null)

          }}

          className="h-8"

        />

        <Button size="sm" className="h-8" disabled={!naming.trim()} onClick={done}>

          Save

        </Button>

        <Button variant="ghost" size="icon-sm" className="h-8" onClick={() => setNaming(null)} aria-label="Cancel">

          <X />

        </Button>

      </div>
    )
  }
  return (
    <div className="flex gap-2">

      <div className="min-w-0 flex-1">

        <Select

          value={names.includes(preset) ? preset : ''}

          onValueChange={applyPreset}

          options={names}

          disabled={!names.length}

          placeholder={names.length ? 'Pick a saved look' : 'No presets yet'}

        />

      </div>

      <Tooltip content="Save the look as it is now under a name">

        <Button variant="outline" size="sm" className="h-8" onClick={() => setNaming(names.includes(preset) ? preset : '')}>

          <Save /> Save

        </Button>

      </Tooltip>

      {names.includes(preset) && (

        <Tooltip content={`Delete “${preset}”`}>

          <Button variant="ghost" size="icon-sm" className="h-8" onClick={() => void deletePreset(preset)} aria-label="Delete the preset">

            <Trash2 />

          </Button>

        </Tooltip>

      )}

    </div>
  )
}

function Letters() {
  const options = useStore((state) => state.options)
  const look = useStore((state) => state.look)
  const setLook = useStore((state) => state.setLook)
  const items = useStore((state) => state.items)
  const active = useStore((state) => state.active)
  const matches = useStore((state) => state.matches)
  const matching = useStore((state) => state.matching)
  const matchFonts = useStore((state) => state.matchFonts)
  const fonts = options?.fonts ?? [look.font]
  const target = items.find((item) => item.key === active) ?? items[items.length - 1]
  const shown = matches && target && matches.key === target.key ? matches.fonts : null

  return (
    <Section title="Letters">

      <Field label="Preset" hint="The whole look (font, colors, outline, material and the rest) saved under a name">

        <Presets />

      </Field>

      <Field label="Font">

        <div className="flex gap-2">

          <div className="min-w-0 flex-1">

            <Select

              value={look.font}

              onValueChange={(font) => setLook({ font })}

              options={fonts}

              renderOption={(font) => <span style={{ fontFamily: fontFamilyOf(font) }}>{font}</span>}

            />

          </div>

          <Tooltip content="Find the fonts most like the old letters of the active line">

            <Button

              variant="outline"

              size="sm"

              className="h-8"

              disabled={!target || matching}

              onClick={() => target && void matchFonts(target.key)}

            >

              {matching ? <LoaderCircle className="animate-spin" /> : <ScanSearch />} Match

            </Button>

          </Tooltip>

        </div>

      </Field>

      {shown && shown.length > 0 && (

        <div className="flex flex-wrap gap-1">

          {shown.map((match, index) => (

            <Button

              key={match.name}

              variant={match.name === look.font ? 'secondary' : 'ghost'}

              size="sm"

              className="h-7 border px-2 text-[13px]"

              style={{ fontFamily: fontFamilyOf(match.name) }}

              onClick={() => setLook({ font: match.name })}

            >

              {index + 1}. {match.name}

            </Button>

          ))}

        </div>

      )}

      <div className="flex items-end gap-3">

        <Field label="Color">

          <label

            className={cn(

              'flex h-8 w-24 cursor-pointer items-center gap-2 rounded-md border border-input px-2',

              look.ownColor && 'opacity-50',

            )}

          >

            <input

              type="color"

              value={look.color}

              onChange={(event) => setLook({ color: event.target.value, ownColor: false })}

              className="size-5 cursor-pointer appearance-none border-0 bg-transparent p-0 [&::-webkit-color-swatch]:rounded [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0"

            />

            <span className="font-mono text-xs uppercase">{look.color}</span>

          </label>

        </Field>

        <div className="flex-1 pb-1.5">

          <SwitchField

            label="Old letters' color"

            hint="Every line keeps the color its old letters had. Picking a color turns this off."

            checked={look.ownColor}

            onChange={(ownColor) => setLook({ ownColor })}

          />

        </div>

      </div>

      <SwitchField

        label="Second color"

        hint="The lower part of each line in a second color, as on signs and logos"

        checked={look.twoColors}

        onChange={(twoColors) => setLook({ twoColors })}

      />

      {look.twoColors && (

        <div className="grid grid-cols-[auto_1fr] items-end gap-3">

          <ColorField label="Lower color" value={look.color2} onChange={(color2) => setLook({ color2 })} />

          <SliderField

            label="Sharp / smooth"

            hint="0: the two colors meet at the middle of the line; 100%: one runs into the other"

            value={look.split}

            onChange={(split) => setLook({ split })}

            min={0}

            max={1}

            step={0.05}

            format={percent}

          />

        </div>

      )}

      <SliderField

        label="Size"

        hint="1.00 gives letters as tall as the old ones"

        value={look.size}

        onChange={(size) => setLook({ size })}

        min={0.5}

        max={2}

        step={0.01}

        format={fixed(2)}

      />

      <SliderField

        label="Spread to the old width"

        hint="A text shorter than the old one is spread towards the old width: spacing first, then wider letters"

        value={look.fill}

        onChange={(fill) => setLook({ fill })}

        min={0}

        max={1}

        step={0.05}

        format={percent}

      />

      <SwitchField

        label="Strokes as thick as the old letters'"

        checked={look.matchWeight}

        onChange={(matchWeight) => setLook({ matchWeight })}

      />

      <SliderField

        label="Thinner / bolder"

        value={look.weight}

        onChange={(weight) => setLook({ weight })}

        min={-1}

        max={1}

        step={0.05}

        format={fixed(2)}

        disabled={look.matchWeight}

      />

      <div className="grid grid-cols-[1fr_auto] items-end gap-3">

        <SliderField

          label="Hand-made unevenness"

          hint="Tilts, shifts and resizes each letter a little, as hand lettering is"

          value={look.uneven}

          onChange={(uneven) => setLook({ uneven })}

          min={0}

          max={1}

          step={0.05}

          format={percent}

        />

        <Tooltip content="Another roll of the dice for the unevenness">

          <Button

            variant="outline"

            size="sm"

            disabled={!look.uneven}

            onClick={() => setLook({ seed: (look.seed + 1) % 1000 })}

          >

            <Sparkles /> {look.seed}

          </Button>

        </Tooltip>

      </div>

    </Section>
  )
}

function OutlineAndShadow() {
  const look = useStore((state) => state.look)
  const setLook = useStore((state) => state.setLook)
  return (
    <Section title="Outline and shadow" defaultOpen={look.outline > 0 || look.shadow > 0}>

      <div className="grid grid-cols-[auto_1fr] items-end gap-3">

        <ColorField label="Outline" value={look.outlineColor} onChange={(outlineColor) => setLook({ outlineColor })} />

        <SliderField

          label="Width"

          hint="In letter heights; 0 for no outline"

          value={look.outline}

          onChange={(outline) => setLook({ outline })}

          min={0}

          max={0.3}

          step={0.005}

          format={fixed(3)}

        />

      </div>

      <div className="grid grid-cols-[auto_1fr] items-end gap-3">

        <ColorField label="Shadow" value={look.shadowColor} onChange={(shadowColor) => setLook({ shadowColor })} />

        <SliderField

          label="Strength"

          hint="0 for no shadow"

          value={look.shadow}

          onChange={(shadow) => setLook({ shadow })}

          min={0}

          max={1}

          step={0.05}

          format={percent}

        />

      </div>

      <div className="grid grid-cols-3 gap-3">

        <SliderField

          label="Right"

          value={look.shadowX}

          onChange={(shadowX) => setLook({ shadowX })}

          min={-0.5}

          max={0.5}

          step={0.01}

          format={fixed(2)}

          disabled={!look.shadow}

        />

        <SliderField

          label="Down"

          value={look.shadowY}

          onChange={(shadowY) => setLook({ shadowY })}

          min={-0.5}

          max={0.5}

          step={0.01}

          format={fixed(2)}

          disabled={!look.shadow}

        />

        <SliderField

          label="Blur"

          value={look.shadowBlur}

          onChange={(shadowBlur) => setLook({ shadowBlur })}

          min={0}

          max={0.5}

          step={0.01}

          format={fixed(2)}

          disabled={!look.shadow}

        />

      </div>

    </Section>
  )
}

function Material() {
  const look = useStore((state) => state.look)
  const setLook = useStore((state) => state.setLook)
  const label = EFFECTS.find((effect) => effect.value === look.effect)?.label ?? 'Paint'
  return (
    <Section title="Material" defaultOpen={look.effect !== 'none'}>

      <Field label="The letters are" hint="Paint, or a material with a look of its own">

        <Select

          value={label}

          onValueChange={(chosen) => setLook({ effect: EFFECTS.find((effect) => effect.label === chosen)?.value ?? 'none' })}

          options={EFFECTS.map((effect) => effect.label)}

        />

      </Field>

      <SliderField

        label="Strength"

        value={look.effectStrength}

        onChange={(effectStrength) => setLook({ effectStrength })}

        min={0}

        max={1}

        step={0.05}

        format={percent}

        disabled={look.effect === 'none'}

      />

    </Section>
  )
}

function Surface() {
  const look = useStore((state) => state.look)
  const setLook = useStore((state) => state.setLook)
  return (
    <Section

      title="On the surface"

      aside={

        (look.shiftX !== 0 || look.shiftY !== 0) && (

          <Button

            variant="ghost"

            size="sm"

            className="h-6 px-2 text-muted-foreground"

            onClick={() => setLook({ shiftX: 0, shiftY: 0 })}

          >

            <RotateCcw className="size-3" /> Place

          </Button>

        )

      }

    >

      <SliderField

        label="Light and shadow of the surface"

        hint="Where the surface under a letter is brighter or darker, so is the letter"

        value={look.shading}

        onChange={(shading) => setLook({ shading })}

        min={0}

        max={1}

        step={0.05}

        format={percent}

      />

      <SliderField

        label="Follow the folds"

        hint="The letters bend with the folds and bumps of the surface, as its light and shadow show them"

        value={look.relief}

        onChange={(relief) => setLook({ relief })}

        min={0}

        max={1}

        step={0.05}

        format={percent}

      />

      <div className="grid grid-cols-2 gap-3">

        <SliderField

          label="Opacity"

          value={look.opacity}

          onChange={(opacity) => setLook({ opacity })}

          min={0.3}

          max={1}

          step={0.01}

          format={percent}

        />

        <SliderField

          label="Soft edges"

          value={look.soften}

          onChange={(soften) => setLook({ soften })}

          min={0}

          max={3}

          step={0.1}

          format={(value) => `${value.toFixed(1)} px`}

        />

        <SliderField

          label="Move right"

          hint="In letter heights"

          value={look.shiftX}

          onChange={(shiftX) => setLook({ shiftX })}

          min={-2}

          max={2}

          step={0.02}

          format={fixed(2)}

        />

        <SliderField

          label="Move down"

          hint="In letter heights"

          value={look.shiftY}

          onChange={(shiftY) => setLook({ shiftY })}

          min={-2}

          max={2}

          step={0.02}

          format={fixed(2)}

        />

      </div>

    </Section>
  )
}

function ModelPass() {
  const options = useStore((state) => state.options)
  const model = useStore((state) => state.model)
  const setModel = useStore((state) => state.setModel)
  const prompt = useStore((state) => state.prompt)
  const negative = useStore((state) => state.negative)
  const setPrompt = useStore((state) => state.setPrompt)
  const setNegative = useStore((state) => state.setNegative)

  if (options && !options.canBlend) {
    return (
      <Section title="Model pass">

        <p className="text-xs leading-relaxed text-muted-foreground">

          In ComfyUI the model pass belongs to the workflow: feed the node's <b>image</b> and <b>mask</b> outputs to an

          inpainting pass at a denoise of 0.25 to 0.35. What you select and type here is kept in the node.

        </p>

      </Section>
    )
  }

  const samplers = options?.samplers.length ? options.samplers : [model.sampler]
  const controlnets = options?.controlnets ?? []
  const guide = model.guide && controlnets.includes(model.guide) ? model.guide : OFF
  return (
    <Section title="Model pass">

      <SliderField

        label="Denoising strength"

        hint="0.25 to 0.35 keeps the letters readable; higher brings the gibberish back"

        value={model.strength}

        onChange={(strength) => setModel({ strength })}

        min={0.05}

        max={0.6}

        step={0.01}

        format={fixed(2)}

      />

      {controlnets.length > 0 && (

        <>

          <Field

            label="Guide by the letters' edges"

            hint="A ControlNet model (canny or lineart) holds the shapes of the letters, so the strength can go higher without the model changing them."

          >

            <Select

              value={guide}

              onValueChange={(chosen) => setModel({ guide: chosen === OFF ? '' : chosen })}

              options={[OFF, ...controlnets]}

            />

          </Field>

          {model.guide && (

            <SliderField

              label="Guide weight"

              hint="How firmly the edges hold the letters"

              value={model.guideWeight}

              onChange={(guideWeight) => setModel({ guideWeight })}

              min={0.1}

              max={1.5}

              step={0.05}

              format={fixed(2)}

            />

          )}

        </>
      )}
      <SliderField
        label="Variants"
        hint="Passes with different seeds, to pick the one whose letters came out right. Each takes as long as one pass."
        value={model.variants}
        onChange={(variants) => setModel({ variants })}
        min={1}
        max={4}
        step={1}
      />
      <Field label="Prompt" hint="Taken from the image when it carries one. An empty prompt works too.">

        <Textarea value={prompt} onChange={(event) => setPrompt(event.target.value)} rows={3} placeholder="Empty works too" />

      </Field>
      <SwitchField

        label="Leave out words that ask for text"

        hint="Tags such as “text on the shirt” or “sign that says …” make the model write letters of its own. They are left out of this pass, and “text, letters, watermark” goes into the negative."

        checked={model.cleanPrompt}

        onChange={(cleanPrompt) => setModel({ cleanPrompt })}

      />
      <Field label="Negative prompt">

        <Textarea value={negative} onChange={(event) => setNegative(event.target.value)} rows={2} />

      </Field>
      <Field label="Sampler">

        <Select value={model.sampler} onValueChange={(sampler) => setModel({ sampler })} options={samplers} />

      </Field>
      <div className="grid grid-cols-2 gap-3">

        <SliderField label="Steps" value={model.steps} onChange={(steps) => setModel({ steps })} min={4} max={60} step={1} />

        <SliderField label="CFG" value={model.cfg} onChange={(cfg) => setModel({ cfg })} min={1} max={15} step={0.5} />

        <SliderField

          label="Resolution"

          hint="The size the spot is enlarged to: 1024 for SDXL, 512 to 768 for SD 1.5"

          value={model.resolution}

          onChange={(resolution) => setModel({ resolution })}

          min={512}

          max={1536}

          step={64}

        />

        <SliderField

          label="Context"

          hint="How much of the surroundings the model sees, in pixels"

          value={model.padding}

          onChange={(padding) => setModel({ padding })}

          min={16}

          max={256}

          step={8}

          format={(value) => `${value} px`}

        />

      </div>
    </Section>
  )
}

/** Everything that is set rather than clicked: the texts, the look, the model pass. */
export function SidePanel() {
  const options = useStore((state) => state.options)
  const session = useStore((state) => state.session)
  const items = useStore((state) => state.items)
  const blending = useStore((state) => state.blending)
  const blend = useStore((state) => state.blend)
  const ready = !!session && items.some((item) => item.text.trim() || item.erase)

  return (
    <aside className="flex w-[340px] shrink-0 flex-col border-l bg-card">

      <div className="scroll-thin min-h-0 flex-1 overflow-y-auto">

        <Lines />

        <Finding />

        <Letters />

        <OutlineAndShadow />

        <Material />

        <Surface />

        <ModelPass />

      </div>

      {options?.canBlend !== false && (

        <div className="border-t p-3">

          <Button size="lg" className="w-full" disabled={!ready || blending} onClick={() => void blend()}>

            {blending ? <LoaderCircle className="animate-spin" /> : <Sparkles />}

            Blend in with the model

          </Button>

          <p className="mt-1.5 text-center text-[11px] text-muted-foreground">Ctrl + Enter</p>

        </div>

      )}

    </aside>
  )
}