File size: 31,491 Bytes
55306cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useRef, useState, type ReactNode } from 'react'
import { useAssetStyles } from '../assetStyles'
import { lineFates } from '../lines'
import { useStore } from '../store'
import { BUBBLE_SHAPES, BUBBLE_TAILS, textless } from '../geometry'
import { BubblesField } from './BubblesField'
import { MarksBar } from './MarksBar'
import { firstLook, inked, KINDS, LOOKS, painted, STRENGTH } from '../regionKinds'
import type { BubbleShape, BubbleTail, Region, RegionKind, RegionLook, SectionId, Tool } from '../types'
import { Button, ColorField, Icon, IconButton, Section, Segmented, Select, Slider, Toggle } from './controls'

type FieldName = 'text' | 'caption' | 'sfx'

interface SliderSpec {
  key: string
  label: string
  hint: string
  min: number
  max: number
  step: number
}

// A label is short enough for one line; the hint says the same in full, on hover.
const ALL_TEXT: SliderSpec[] = [
  { key: 'soften', label: 'Soften edges, px', hint: 'Blur the letter edges, in pixels', min: 0, max: 3, step: 0.1 },
  { key: 'grain', label: 'Uneven ink', hint: 'Ink that is thinner in places, like a worn stamp', min: 0, max: 1, step: 0.05 },
  { key: 'arc', label: 'Bend into an arc', hint: 'Curve the lines up or down', min: -1, max: 1, step: 0.05 },
  { key: 'rotation', label: 'Tilt, °', hint: 'Tilt all text, degrees', min: -45, max: 45, step: 0.5 },
  { key: 'opacity', label: 'Opacity', hint: 'How solid all text is', min: 0.1, max: 1, step: 0.05 },
  { key: 'gradient_angle', label: 'Gradient angle, °', hint: 'Which way every gradient runs: 0 top to bottom, 90 left to right', min: -180, max: 180, step: 5 },
  { key: 'drip', label: 'Drips', hint: 'Drips run down from the letters: none to many and long', min: 0, max: 1, step: 0.05 },
]
const BUBBLE_GLOW: SliderSpec = {
  key: 'caption_bubble_glow',
  label: 'Bubble glow',
  hint: "A glow of the outline's color round the caption's bubble: none to strong",
  min: 0,
  max: 1,
  step: 0.05,
}
const TAIL_ANGLE: SliderSpec = {
  key: 'caption_tail_angle',
  label: 'Tail direction, °',
  hint: 'Where the tail points, degrees: 0 right, 90 down, 180 left, 270 up',
  min: 0,
  max: 360,
  step: 5,
}
const BUBBLES: SliderSpec[] = [
  { key: 'bubble_size', label: 'Largest font, %', hint: 'Largest font in a bubble, % of image height', min: 1, max: 30, step: 0.5 },
  {
    key: 'bubble_min_size',
    label: 'Smallest font, %',
    hint: 'Smallest font still readable, % of image height; longer text goes elsewhere',
    min: 0.5,
    max: 10,
    step: 0.1,
  },
  { key: 'margin', label: 'Gap to the edge', hint: "Space between the text and the bubble's edge", min: 0, max: 0.3, step: 0.01 },
  { key: 'white_threshold', label: 'Darkest bubble fill', hint: 'The darkest fill still taken for a bubble (0-255)', min: 40, max: 255, step: 1 },
  {
    key: 'bubble_stroke_width',
    label: 'Outline width',
    hint: 'Outline around text on a bubble, as a share of the font size. 0 = none. Also used in your own bubbles and in a caption put in a bubble.',
    min: 0,
    max: 0.3,
    step: 0.01,
  },
  { key: 'bubble_glow', label: 'Glow of drawn bubbles', hint: 'A glow round the bubbles you draw yourself (areas with a bubble fill): none to strong', min: 0, max: 1, step: 0.05 },
]
const CAPTION: SliderSpec[] = [
  { key: 'free_size', label: 'Font size, %', hint: 'Caption font size, % of image height', min: 1, max: 30, step: 0.5 },
  { key: 'stroke_width', label: 'Outline width', hint: 'Caption outline width', min: 0, max: 0.5, step: 0.01 },
  { key: 'shadow', label: 'Shadow', hint: 'Caption shadow strength', min: 0, max: 1, step: 0.05 },
]
const EFFECTS: SliderSpec[] = [
  { key: 'sfx_size', label: 'Font size, %', hint: 'Effect font size, % of image height', min: 1, max: 30, step: 0.5 },
  { key: 'sfx_tilt', label: 'Largest tilt, °', hint: 'Effects tilt at random up to this many degrees', min: 0, max: 45, step: 1 },
  { key: 'sfx_opacity', label: 'Opacity', hint: 'How solid the effects are', min: 0.1, max: 1, step: 0.05 },
  { key: 'sfx_glow', label: 'Glow', hint: 'A glow round the letters of an effect: none to strong', min: 0, max: 1, step: 0.05 },
]
const CUSTOM_MOOD: SliderSpec[] = [
  { key: 'jitter', label: 'Letters wobble', hint: 'Letters move off the line', min: 0, max: 1, step: 0.05 },
  { key: 'size_jitter', label: 'Letter sizes vary', hint: 'Letters differ in size', min: 0, max: 1, step: 0.05 },
  { key: 'rough', label: 'Ragged edges', hint: 'Letter edges are torn', min: 0, max: 1, step: 0.05 },
  { key: 'line_tilt', label: 'Lines tilt, °', hint: 'Each line tilts a little, degrees', min: 0, max: 15, step: 0.5 },
  { key: 'line_shift', label: 'Lines shift', hint: 'Lines move sideways', min: 0, max: 1, step: 0.05 },
  { key: 'line_spacing', label: 'Line spacing', hint: 'Space between lines', min: 0.7, max: 1.6, step: 0.02 },
]

const FILLS: { value: Region['fill']; label: string }[] = [
  { value: 'none', label: 'On the art' },
  { value: 'light', label: 'Light bubble' },
  { value: 'dark', label: 'Dark bubble' },
  { value: 'black', label: 'Black' },
  { value: 'gray', label: 'Gray message' },
  { value: 'blue', label: 'Blue message' },
  { value: 'soft', label: 'Soft patch' },
]
const FILL_LABELS = FILLS.map((entry) => entry.label)

/** What the area's text sits on, from a list: there are too many to lay out in a row. */
function FillSelect({ value, onChange }: { value: Region['fill']; onChange: (fill: Region['fill']) => void }) {
  return (
    <Select

      ariaLabel="What the text sits on"

      value={FILLS.find((entry) => entry.value === value)?.label ?? FILL_LABELS[0]}

      options={FILL_LABELS}

      onChange={(label) => onChange(FILLS.find((entry) => entry.label === label)?.value ?? value)}

    />
  )
}

const kindLabel = (kind: RegionKind) => KINDS.find((entry) => entry.value === kind)?.label ?? kind
const KIND_LABELS = KINDS.map((entry) => entry.label)

/** What an area is for, from a list: there are too many to lay out in a row. */
function KindSelect({ value, onChange }: { value: RegionKind; onChange: (kind: RegionKind) => void }) {
  return (
    <Select

      ariaLabel="What the area is for"

      value={kindLabel(value)}

      options={KIND_LABELS}

      onChange={(label) => onChange(KINDS.find((entry) => entry.label === label)?.value ?? value)}

    />
  )
}

/** How the kind looks, where it has looks to choose from. */
function LookRow({ kind, value, onChange }: { kind: RegionKind; value: RegionLook | undefined; onChange: (look: RegionLook) => void }) {
  const looks = LOOKS[kind]
  if (!looks) return null
  return <Segmented<RegionLook> compact value={value ?? looks[0].value} options={looks} onChange={onChange} />
}

/** The shape of a bubble template, from a list. */
function ShapeSelect({ value, onChange }: { value: BubbleShape; onChange: (shape: BubbleShape) => void }) {
  const label = (shape: string) => shape[0].toUpperCase() + shape.slice(1)
  return (
    <Select

      ariaLabel="Bubble shape"

      value={label(value)}

      options={BUBBLE_SHAPES.map(label)}

      onChange={(next) => onChange((BUBBLE_SHAPES.find((shape) => label(shape) === next) ?? value) as BubbleShape)}

    />
  )
}

/** What to do with the tool in hand, in a line; shown while no area is picked. */
const TOOL_HINTS: Record<Tool, string> = {
  off: 'Pick a drawing tool on the left, or click an area to change it.',
  bubble: 'Drag on the image where the bubble goes, or just click.',
  brush: 'Paint where it goes: the words, a mark, or a cover. A field opens beside it for the text or the mark.',
  eraser: 'Rub out what was painted.',
}

/** The areas drawn by hand. The picked one shows its settings (its text is typed on the image);

 * the others are a line each. What the tool in hand will draw next shows only while no area is

 * picked, so a bubble's shape and tail are never on the panel twice. */
function AreasPanel() {
  const tool = useStore((state) => state.tool)
  const brush = useStore((state) => state.brush)
  const pickedId = useStore((state) => state.region)
  const regions = useStore((state) => state.slots[state.source]?.regions)
  const stamp = useStore((state) => state.stamp)
  const paint = useStore((state) => state.paint)
  const { setBrush, pickRegion, changeRegion, removeRegion, undoShape, render, setStamp, setPaint, reshape } = useStore.getState()
  if (!regions) return null
  const picked = regions.some((region) => region.id === pickedId) ? pickedId : null
  return (
    <>

      {picked === null && tool === 'bubble' && (

        <>

          <ShapeSelect value={stamp.shape} onChange={(shape) => setStamp({ shape })} />

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

            <Select label="Tail" value={stamp.tail} options={BUBBLE_TAILS} onChange={(tail) => setStamp({ tail: tail as BubbleTail })} />

            <Select label="Bubble color" value={stamp.fill} options={['light', 'dark', 'black', 'gray', 'blue', 'soft']} onChange={(fill) => setStamp({ fill: fill as Exclude<Region['fill'], 'none'> })} />

          </div>

        </>

      )}

      {picked === null && tool === 'brush' && (

        <>

          <KindSelect value={paint.kind} onChange={(kind) => setPaint({ kind })} />

          <LookRow kind={paint.kind} value={paint.look} onChange={(look) => setPaint({ look })} />

        </>
      )}
      {picked === null && (tool === 'brush' || tool === 'eraser') && (
        <Slider

          label={tool === 'eraser' ? 'Eraser width, %' : 'Brush width, %'}

          hint="Width, % of the image's shorter side"

          value={Math.round(brush * 100)}

          min={1}

          max={30}

          step={1}

          onChange={(value) => setBrush(value / 100)}

          onCommit={() => undefined}

        />
      )}
      {picked === null && <p className="text-[11px] leading-snug text-cl-muted">{TOOL_HINTS[tool]}</p>}
      {regions.map((region, index) =>
        region.id !== picked ? (
          <div key={region.id} className="flex items-center gap-1">

            <button

              type="button"

              onClick={() => pickRegion(region.id)}

              className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded border border-cl-border px-2 text-left hover:border-cl-muted focus-visible:outline focus-visible:outline-2 focus-visible:outline-cl-accent"

            >

              <span className={`h-2.5 w-2.5 shrink-0 rounded-sm ${region.kind === 'keepout' ? 'bg-cl-danger' : 'bg-cl-hand'}`} aria-hidden="true" />

              <span className="shrink-0 text-xs font-medium text-cl-text">Area {index + 1}</span>

              <span className="shrink-0 text-[11px] text-cl-muted">{kindLabel(region.kind).toLowerCase()}</span>

              <span className="min-w-0 flex-1 truncate text-[11px] text-cl-muted">

                {LOOKS[region.kind]

                  ? (LOOKS[region.kind]?.find((look) => look.value === (region.look ?? firstLook(region.kind)))?.label ?? '—')

                  : !textless(region) && region.text.trim()

                    ? region.text.trim().replace(/\s+/g, ' ')

                    : '—'}

              </span>

            </button>

            <IconButton label={`Delete area ${index + 1}`} onClick={() => removeRegion(region.id)}>

              <Icon>

                <path d="M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.7 8.5h5.6l.7-8.5" />

              </Icon>

            </IconButton>

          </div>
        ) : (
          <div key={region.id} className="flex flex-col gap-1.5 rounded border border-cl-accent p-2">

            <div className="flex items-center justify-between gap-2">

              <span className="text-xs font-medium text-cl-text">Area {index + 1}</span>

              <span className="flex items-center">

                <Button variant="quiet" onClick={() => undoShape(region.id)} title="Take back the last thing drawn in this area">

                  Undo stroke

                </Button>

                <Button variant="quiet" onClick={() => removeRegion(region.id)}>

                  Delete

                </Button>

                <Button

                  variant="quiet"

                  onClick={() => {

                    void render()

                    pickRegion(null)

                  }}

                >

                  Done

                </Button>

              </span>

            </div>

            <KindSelect

              value={region.kind}

              onChange={(kind) => changeRegion(region.id, { kind, look: firstLook(kind), ...(inked(kind) ? {} : { color: undefined }) })}

            />

            <LookRow kind={region.kind} value={region.look} onChange={(look) => changeRegion(region.id, { look })} />

            {painted(region.kind) && STRENGTH[region.kind] && (region.kind !== 'censor' || region.look === 'mosaic' || region.look === 'blur') && (

              <Slider

                label={STRENGTH[region.kind]?.label ?? 'Strength, %'}

                hint={STRENGTH[region.kind]?.hint ?? ''}

                value={Math.round((region.scale ?? 1) * 100)}

                min={30}

                max={400}

                step={10}

                onChange={(value) => changeRegion(region.id, { scale: value / 100 }, false)}

                onCommit={() => void render()}

              />

            )}

            {inked(region.kind) && (

              <ColorField

                label={region.kind === 'mark' ? 'Mark color' : 'Color'}

                hint={region.kind === 'mark' ? 'auto: white with a dark outline' : 'auto: black'}

                value={region.color ?? 'auto'}

                onDraft={(next) => changeRegion(region.id, { color: next === 'auto' ? undefined : next }, false)}

                onCommit={(next) => changeRegion(region.id, { color: next === 'auto' ? undefined : next })}

              />

            )}

            {(region.kind === 'tone' || (region.kind === 'lines' && region.look === 'speed') || (region.kind === 'censor' && region.look === 'ghost')) && (

              <Slider

                label="Angle, °"

                hint={region.kind === 'censor' ? 'Which way the copies trail: 0 to the right, 90 down' : 'Which way the pattern runs'}

                value={region.rotation ?? 0}

                min={-90}

                max={90}

                step={5}

                onChange={(value) => changeRegion(region.id, { rotation: value }, false)}

                onCommit={() => void render()}

              />

            )}

            {region.template && (

              <>

                <ShapeSelect value={region.template.shape} onChange={(shape) => reshape(region.id, { shape })} />

                <Select label="Tail" value={region.template.tail} options={BUBBLE_TAILS} onChange={(tail) => reshape(region.id, { tail: tail as BubbleTail })} />

              </>
            )}
            {region.kind === 'text' && <FillSelect value={region.fill} onChange={(fill) => changeRegion(region.id, { fill })} />}
            {(region.kind === 'text' || region.kind === 'sfx') && region.shapes.some((shape) => shape.type === 'stroke') && (
              <Toggle checked={region.follow === true} onChange={(follow) => changeRegion(region.id, { follow })} label="Write along the brush stroke" />
            )}
            {(region.kind === 'text' || region.kind === 'sfx') && region.follow === true && (
              <Toggle checked={region.flip === true} onChange={(flip) => changeRegion(region.id, { flip })} label="Turn the text round" />
            )}
            {(region.kind === 'text' || region.kind === 'sfx' || region.kind === 'mark') && (
              <>

                <Slider

                  label="Size, %"

                  hint="Text size, % of what the area gives"

                  value={Math.round((region.scale ?? 1) * 100)}

                  min={30}

                  max={300}

                  step={5}

                  onChange={(value) => changeRegion(region.id, { scale: value / 100 }, false)}

                  onCommit={() => void render()}

                />

                {region.follow !== true && (

                  <Slider

                    label={region.rotation === undefined && region.kind === 'sfx' ? 'Tilt, ° (random now)' : 'Tilt, °'}

                    hint="Tilt of the text, degrees"

                    value={region.rotation ?? 0}

                    min={-90}

                    max={90}

                    step={1}

                    onChange={(value) => changeRegion(region.id, { rotation: value }, false)}

                    onCommit={() => void render()}

                  />

                )}

                {region.follow !== true && region.rotation !== undefined && (

                  <Button variant="quiet" onClick={() => changeRegion(region.id, { rotation: undefined })}>

                    {region.kind === 'sfx' ? 'Back to a random tilt' : 'Back to no tilt of its own'}

                  </Button>

                )}

              </>
            )}
          </div>
        ),
      )}
    </>
  )
}

/** A small heading inside a section. */
function Group({ title, children }: { title: string; children: ReactNode }) {
  return (
    <div className="flex flex-col gap-2">

      <div className="mt-1 text-[11px] uppercase tracking-wide text-cl-muted">{title}</div>

      {children}

    </div>
  )
}

function Sliders({ specs }: { specs: SliderSpec[] }) {
  const settings = useStore((state) => state.settings)
  const setSetting = useStore((state) => state.setSetting)
  const render = useStore((state) => state.render)
  return (
    <>

      {specs.map((spec) => (

        <Slider

          key={spec.key}

          label={spec.label}

          hint={spec.hint}

          value={Number(settings[spec.key] ?? 0)}

          min={spec.min}

          max={spec.max}

          step={spec.step}

          onChange={(value) => setSetting(spec.key, value, false)}

          onCommit={() => void render()}

        />

      ))}

    </>
  )
}

function Check({ name, label }: { name: string; label: string }) {
  const value = useStore((state) => Boolean(state.settings[name]))
  const setSetting = useStore((state) => state.setSetting)
  return <Toggle checked={value} onChange={(next) => setSetting(name, next)} label={label} />
}

const GRADIENT_HINT = 'The color the letters fade to, top to bottom (bubbles and caption share it). auto: one color, no gradient'

function Color({ name, label, hint }: { name: string; label: string; hint?: string }) {
  const value = useStore((state) => String(state.settings[name] ?? 'auto'))
  const setSetting = useStore((state) => state.setSetting)
  return (
    <ColorField

      label={label}

      hint={hint ?? `${label}: left to the script, or a color of your own`}

      value={value}

      onDraft={(next) => setSetting(name, next, false)}

      onCommit={(next) => setSetting(name, next, true)}

    />
  )
}

/** The sliders behind the mood "custom". There is one set of them: every text set to custom follows it. */
function CustomMood() {
  return (
    <Group title="Custom mood (shared by all text)">

      <Sliders specs={CUSTOM_MOOD} />

    </Group>
  )
}

/** What a folded section says of its text: the first line that has something in it, cut short. */
function firstLine(text: string) {
  const line = text.split('\n').find((entry) => entry.trim()) ?? ''
  const short = line.trim()
  if (!short) return 'empty'
  return short.length > 24 ? `${short.slice(0, 23)}…` : short
}

export function SidePanel() {
  const options = useStore((state) => state.options)
  const settings = useStore((state) => state.settings)
  const fields = {
    text: useStore((state) => state.text),
    caption: useStore((state) => state.caption),
    sfx: useStore((state) => state.sfx),
  }
  const auto = useStore((state) => state.auto)
  const embedded = useStore((state) => state.embedded)
  const comfy = useStore((state) => state.comfy)
  const open = useStore((state) => state.open)
  const areaCount = useStore((state) => state.slots[state.source]?.regions.length ?? 0)
  const slot = useStore((state) => state.slots[state.source])
  const { setField, setSetting, setAuto, setOpen, moveEffects, resetLook, render } = useStore.getState()

  const areas = useRef<Record<FieldName, HTMLTextAreaElement | null>>({ text: null, caption: null, sfx: null })
  const [more, setMore] = useState<Record<FieldName, boolean>>({ text: false, caption: false, sfx: false })
  const [keepFonts, setKeepFonts] = useState(true)
  // The fonts and the shapes of the marks, for the lists and the buttons to draw with.
  const fontOf = useAssetStyles(options)

  if (!options) return null
  const list =(key: string, label: string, choices: string[], fonts = false) => (
    <Select

      key={key}

      label={label}

      value={String(settings[key] ?? '')}

      options={choices}

      onChange={(value) => setSetting(key, value)}

      fontOf={fonts ? fontOf : undefined}

    />
  )

  /** The bar over a text field: bigger words, marks, and emptying the field. */
  const bar = (name: FieldName, label: string) => (
    <MarksBar

      label={label}

      target={() => areas.current[name]}

      value={fields[name]}

      onChange={(next) => setField(name, next)}

      onClear={() => {

        setField(name, '')

        void render()

      }}

    />
  )
  const field = (name: FieldName, label: string, hint: string, rows: number) => (
    <div>

      {bar(name, label)}

      <textarea

        ref={(element) => {

          areas.current[name] = element

        }}

        value={fields[name]}

        rows={rows}

        placeholder={hint}

        spellCheck={false}

        onChange={(event) => setField(name, event.target.value)}

        onBlur={() => void render()}

        onKeyDown={(event) => {

          if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) void render()

        }}

        className="block w-full resize-y rounded-b border border-cl-border bg-cl-raised px-2 py-1.5 text-sm placeholder:text-cl-muted"

      />

    </div>
  )
  /** The button that shows the rest of a kind's settings, and those settings. */
  const rest = (name: FieldName, children: ReactNode) => (
    <>

      <div>

        <Button variant="quiet" onClick={() => setMore({ ...more, [name]: !more[name] })}>

          {more[name] ? 'Less' : 'More…'}

        </Button>

      </div>

      {more[name] && children}

    </>
  )
  const drawn = settings.caption_bubble !== 'none'
  const fold = (id: SectionId) => (value: boolean) => setOpen(id, value)

  return (
    <aside className="relative flex w-80 shrink-0 flex-col gap-3 overflow-y-auto border-l border-cl-border bg-cl-surface p-3">

      <Section

        id="cl-bubbles"

        title="Bubbles"

        summary={`${firstLine(fields.text)} · ${String(settings.font ?? '')}`}

        open={open.bubbles}

        onToggle={fold('bubbles')}

      >

        <div>

          {bar('text', 'Bubbles')}

          <BubblesField

            value={fields.text}

            fates={lineFates(fields.text, slot?.applied || null, slot?.items ?? [], slot?.bubbles.length ?? 0, Boolean(settings.spill))}

            onChange={(value) => setField('text', value)}

            onBlurCommit={() => void render()}

            onCtrlEnter={() => void render()}

            placeholder="One line per bubble. An empty line leaves a bubble empty."

            rows={3}

            flatTop

            textareaRef={(element) => {

              areas.current.text = element

            }}

          />

          <p className="mt-1 text-[11px] leading-snug text-cl-muted">

            <code>|</code> starts a new line inside a bubble. <code>[6]</code> at the start of a line sets the largest font for that bubble, % of image height.

          </p>

        </div>

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

          {list('font', 'Font', options.fonts, true)}

          {list('bubble_colors', 'Colors', options.palettes)}

          {list('bubble_mood', 'Mood', options.moods)}

        </div>

        {settings.bubble_mood === 'custom' && <CustomMood />}

        {rest(

          'text',

          <>

            <Check name="erase" label="Erase the letters the model drew" />

            <Check name="spill" label="Text too long for a bubble goes to the caption" />

            <Sliders specs={BUBBLES} />

            {/* The outline's color goes with any Colors preset, so it does not wait for "custom". */}

            {Number(settings.bubble_stroke_width) > 0 && (

              <Color name="bubble_stroke_color" label="Outline color" hint="auto: black on a light bubble, white on a dark one" />

            )}

            {Number(settings.bubble_glow) > 0 && (

              <Color name="bubble_glow_color" label="Glow color" hint="auto: white, or the bubble's own color for gray and blue" />

            )}

            {settings.bubble_colors === 'custom' && (

              <>

                <Color name="text_color" label="Text color (shared with Caption)" />

                <Color name="text_color2" label="Gradient to" hint={GRADIENT_HINT} />

              </>

            )}

          </>,
        )}
      </Section>

      <Section

        id="cl-caption"

        title="Caption"

        summary={`${firstLine(fields.caption)} · ${String(settings.placement ?? '')}`}

        open={open.caption}

        onToggle={fold('caption')}

      >

        {field('caption', 'Caption', 'Text on the art, outside the bubbles.', 2)}

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

          {list('caption_font', 'Font', [options.sameFont, ...options.fonts], true)}

          {list('caption_colors', 'Colors', options.palettes)}

          {list('caption_mood', 'Mood', options.moods)}

          {list('caption_extras', 'Marks around', options.extras)}

          {list('placement', 'Position', options.placements)}

          {list('caption_bubble', 'Put in a bubble', options.shapes)}

          {drawn && list('caption_bubble_theme', 'Bubble color', options.themes)}

          {drawn && list('caption_tail', 'Tail', options.tails)}

        </div>

        {settings.caption_mood === 'custom' && <CustomMood />}

        {rest(

          'caption',

          <>

            {drawn && (

              <p className="text-[11px] leading-snug text-cl-muted">In a bubble, the caption uses the bubble text outline (Bubbles › More).</p>

            )}

            <Sliders specs={CAPTION} />

            {drawn && settings.caption_tail === 'custom' && <Sliders specs={[TAIL_ANGLE]} />}

            {drawn && (

              <>

                <Sliders specs={[BUBBLE_GLOW]} />

                <Color name="caption_bubble_color" label="Bubble fill" hint="auto: the bubble color above" />

                <Color name="caption_bubble_color2" label="Fill gradient to" hint="The color the bubble's fill fades to. auto: one color" />

              </>
            )}
            {settings.caption_colors === 'custom' && (
              <>

                <Color name="text_color" label="Text color (shared with Bubbles)" />

                <Color name="text_color2" label="Gradient to" hint={GRADIENT_HINT} />

                <Color name="stroke_color" label="Outline color" />

              </>
            )}
          </>,
        )}
      </Section>

      <Section

        id="cl-sfx"

        title="Sound effects"

        summary={`${firstLine(fields.sfx)} · ${String(settings.sfx_font ?? '')}`}

        open={open.sfx}

        onToggle={fold('sfx')}

        actions={

          <Button variant="quiet" onClick={moveEffects} title="Put the effects somewhere else">

            Shuffle

          </Button>

        }

      >

        {field('sfx', 'Sound effects', 'One per line: SLAP, THUD x3.', 2)}

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

          {list('sfx_font', 'Font', options.fonts, true)}

          {list('sfx_colors', 'Colors', options.palettes)}

          {list('sfx_mood', 'Mood', options.moods)}

          {list('sfx_extras', 'Marks around', options.extras)}

        </div>

        {settings.sfx_mood === 'custom' && <CustomMood />}

        {rest(

          'sfx',

          <>

            <Sliders specs={EFFECTS} />

            <Color name="sfx_glow_color" label="Glow color" hint="auto: the letters' own color" />

            {settings.sfx_colors === 'custom' && (

              <>

                <Color name="sfx_color" label="Color" />

                <Color name="sfx_color2" label="Gradient to" hint={GRADIENT_HINT} />

              </>
            )}
          </>,
        )}
      </Section>

      <Section

        id="cl-areas"

        title="Areas drawn by hand"

        summary={areaCount ? `${areaCount} ${areaCount === 1 ? 'area' : 'areas'}` : 'none'}

        open={open.areas}

        onToggle={fold('areas')}

      >

        <AreasPanel />

      </Section>

      <Section

        id="cl-all"

        title="All text"

        summary={`capitals ${settings.uppercase ? 'on' : 'off'} · opacity ${String(settings.opacity ?? '')}`}

        open={open.all}

        onToggle={fold('all')}

      >

        <Check name="uppercase" label="Capital letters" />

        <Sliders specs={ALL_TEXT} />

        <Color name="extras_color" label="Marks color" hint="The color of the marks around a caption or an effect. auto: the text's own" />

        <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto_48px] items-center gap-2">

          <span className="truncate text-xs text-cl-text" title="One number picks the wobble pattern, the marks around and the drawn caption bubble">

            Pattern

          </span>

          <Button onClick={() => setSetting('seed', (Number(settings.seed) || 0) + 1)}>

            <Icon>

              <rect x="2.5" y="2.5" width="11" height="11" rx="2" />

              <circle cx="5.5" cy="5.5" r="0.6" />

              <circle cx="8" cy="8" r="0.6" />

              <circle cx="10.5" cy="10.5" r="0.6" />

            </Icon>

            Try another

          </Button>

          <span className="text-right text-[11px] text-cl-muted">#{Number(settings.seed) || 0}</span>

        </div>

        <div className="flex items-center justify-between gap-2">

          <Button onClick={() => resetLook(keepFonts)}>Reset the look</Button>

          <Toggle checked={keepFonts} onChange={setKeepFonts} label="Keep the fonts" />

        </div>

      </Section>

      {embedded && !comfy && (
        <Section id="cl-auto" title="Automatic mode" summary={auto ? 'on' : 'off'} open={open.auto} onToggle={fold('auto')}>

          <div>

            <Toggle id="cl-auto-toggle" checked={auto} onChange={setAuto} label="Letter every new image while it is generated" />

            <p className="mt-1 text-[11px] leading-snug text-cl-muted">

              Uses the three texts above and this look for each image a generation makes.

            </p>

          </div>

        </Section>
      )}
    </aside>
  )
}