-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_ModifyWidgetModal.patch
More file actions
1638 lines (1633 loc) · 187 KB
/
diff_ModifyWidgetModal.patch
File metadata and controls
1638 lines (1633 loc) · 187 KB
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/app/renderer/src/components/editor/widgets/ModifyWidgetModal.tsx b/app/renderer/src/components/editor/widgets/ModifyWidgetModal.tsx
index a7ec5f1..8288556 100644
--- a/app/renderer/src/components/editor/widgets/ModifyWidgetModal.tsx
+++ b/app/renderer/src/components/editor/widgets/ModifyWidgetModal.tsx
@@ -13,347 +13,41 @@ import type { GridItem } from "../canvas/DraggableItem";
import { useScrollLock } from "../../../hooks/useScrollLock";
import LinkPreviewPanel from "./LinkPreviewPanel";
-
-type CarouselEditorItem = {
- id: string;
- mediaType: 'image' | 'video';
- source: string;
- alt: string;
- caption: string;
- poster?: string;
-};
-
-function makeCarouselId(seed?: number) {
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
- const base = Math.random().toString(36).slice(2, 9);
- return seed !== undefined ? `slide-${seed}-${base}` : base;
-}
-
-function normalizeCarouselEditorItems(raw: unknown): CarouselEditorItem[] {
- if (!Array.isArray(raw)) return [];
- return raw.map((entry, idx) => {
- const data = (entry || {}) as CarouselItem;
- const mediaType: 'image' | 'video' = data.mediaType === 'video' ? 'video' : 'image';
- const source = typeof data.src === 'string' && data.src
- ? data.src
- : (typeof data.assetId === 'string' ? data.assetId : '');
- return {
- id: data.id || makeCarouselId(idx),
- mediaType,
- source: source || '',
- alt: typeof data.alt === 'string' ? data.alt : '',
- caption: typeof data.caption === 'string' ? data.caption : '',
- poster: typeof data.poster === 'string' ? data.poster : '',
- } satisfies CarouselEditorItem;
- });
-}
-
-function createBlankCarouselItem(): CarouselEditorItem {
- return {
- id: makeCarouselId(),
- mediaType: 'image',
- source: '',
- alt: '',
- caption: '',
- poster: '',
- };
-}
-
-function serializeCarouselEditorItems(items: CarouselEditorItem[]): CarouselItem[] {
- return items
- .map((item) => ({
- id: item.id,
- mediaType: item.mediaType,
- src: item.source.trim(),
- alt: item.alt.trim() || undefined,
- caption: item.caption.trim() || undefined,
- poster: item.poster?.trim() || undefined,
- }))
- .filter((item) => !!item.src);
-}
-
-const ENTER_SUBMIT_BLOCKED_TYPES = new Set(['checkbox', 'radio', 'range', 'color', 'date', 'datetime-local', 'month', 'week', 'time', 'file']);
-const VIDEO_APPEARANCE_FIELDS = new Set(['shape', 'borderWidth', 'borderRadius', 'borderColor', 'borderStyle', 'backgroundColor']);
-const APPEARANCE_FIELDS_BY_WIDGET: Record<string, ReadonlySet<string>> = {
- image: new Set(['fit', 'radius', 'scale', 'shape', 'borderWidth', 'borderColor', 'borderStyle']),
- text: new Set(['variant', 'align', 'font', 'color', 'fontSize', 'weight', 'italic']),
- link: new Set(['variant', 'font', 'fontSize', 'weight', 'italic']),
- 'nav-link': new Set(['style', 'align', 'color', 'textColor', 'underline', 'font', 'fontSize']),
- project: new Set(['headingLevel', 'font', 'fontSize']),
- contact: new Set(['font', 'fontSize']),
- carousel: new Set(['backgroundColor', 'shape', 'radius', 'borderWidth', 'borderColor', 'borderStyle']),
- 'github-repos': new Set(['layout']),
-};
-const HEX_COLOR_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
-
-function hasAppearanceKeyword(key: string) {
- const normalized = key.toLowerCase();
- if (normalized.includes('color') || normalized.includes('background')) return true;
- if (normalized.includes('border') || normalized.includes('radius')) return true;
- if (normalized.includes('shape')) return true;
- if (normalized.includes('font')) return true;
- if (normalized === 'align' || normalized === 'layout' || normalized === 'weight' || normalized === 'italic') return true;
- if (normalized === 'style' || normalized === 'variant' || normalized === 'underline') return true;
- if (normalized === 'headinglevel' || normalized === 'fit') return true;
- return false;
-}
-
-function isAppearanceField(defType: string | null, key: string) {
- if (!key) return false;
- const overrides = defType ? APPEARANCE_FIELDS_BY_WIDGET[defType] : undefined;
- if (overrides?.has(key)) return true;
- return hasAppearanceKeyword(key);
-}
-const URL_FIELD_HINTS = ['url', 'link', 'href', 'website'];
-const TEXTAREA_FIELD_HINTS = ['description', 'content', 'body', 'text', 'bio', 'summary'];
-const IMAGE_FIELD_HINTS = ['image', 'img', 'photo', 'poster', 'thumb', 'thumbnail', 'cover', 'logo', 'avatar'];
-const VIDEO_FIELD_HINTS = ['video', 'clip', 'movie', 'reel', 'media'];
-const GENERIC_ASSET_HINTS = ['asset', 'src', 'source', 'file'];
-const URL_PROTOCOL_SUGGESTIONS = ['https://', 'http://', 'mailto:', 'tel:'] as const;
-
-const TEXT_VARIANTS = ['paragraph', 'h2', 'h3'] as const;
-const TEXT_ALIGNMENTS = ['left', 'center', 'right'] as const;
-const TEXT_FONTS = ['system', 'serif', 'mono'] as const;
-const TEXT_FORMATS = ['plain', 'markdown'] as const;
-const TEXT_WEIGHTS = ['normal', 'bold'] as const;
-const TEXT_WIDGET_FIELD_KEYS = new Set(['text', 'variant', 'align', 'font', 'color', 'fontSize', 'weight', 'italic', 'ariaLabel', 'ariaDescription', 'format']);
-
-type TextVariantOption = typeof TEXT_VARIANTS[number];
-type TextAlignOption = typeof TEXT_ALIGNMENTS[number];
-type TextFontOption = typeof TEXT_FONTS[number];
-type TextFormatOption = typeof TEXT_FORMATS[number];
-type TextWeightOption = typeof TEXT_WEIGHTS[number];
-
-function createStringGuard<T extends readonly string[]>(options: T) {
- return (value: unknown): value is T[number] => typeof value === 'string' && (options as readonly string[]).includes(value as string);
-}
-
-const isTextVariantValue = createStringGuard(TEXT_VARIANTS);
-const isTextAlignValue = createStringGuard(TEXT_ALIGNMENTS);
-const isTextFontValue = createStringGuard(TEXT_FONTS);
-const isTextFormatValue = createStringGuard(TEXT_FORMATS);
-const isTextWeightValue = createStringGuard(TEXT_WEIGHTS);
-
-const LINK_VARIANTS = ['button', 'text', 'card'] as const;
-const LINK_WIDGET_FIELD_KEYS = new Set(['url', 'label', 'variant', 'iconLeft', 'iconRight', 'font', 'fontSize', 'weight', 'italic', 'ariaLabel', 'ariaDescription']);
-
-type LinkVariantOption = typeof LINK_VARIANTS[number];
-type LinkFontOption = TextFontOption;
-type LinkWeightOption = TextWeightOption;
-
-const isLinkVariantValue = createStringGuard(LINK_VARIANTS);
-const isLinkFontValue = isTextFontValue;
-const isLinkWeightValue = isTextWeightValue;
-
-const NAV_LINK_STYLES = ['link', 'button'] as const;
-const NAV_LINK_WIDGET_FIELD_KEYS = new Set(['label', 'targetPageId', 'style', 'align', 'color', 'textColor', 'underline', 'font', 'fontSize', 'ariaLabel']);
-
-type NavLinkStyleOption = typeof NAV_LINK_STYLES[number];
-
-const isNavLinkStyleValue = createStringGuard(NAV_LINK_STYLES);
-
-type AssetKind = 'image' | 'video' | 'media';
-
-function hasUrlValidation(field: z.ZodTypeAny) {
- const def: any = (field as unknown as { _def?: unknown })._def;
- const checks: Array<{ kind?: string }> = def?.checks ?? [];
- return checks.some(check => check.kind === 'url');
-}
-
-function isLikelyUrlField(key: string, field: z.ZodTypeAny) {
- const lower = key.toLowerCase();
- if (!(field instanceof z.ZodString)) return false;
- if (hasUrlValidation(field)) return true;
- return URL_FIELD_HINTS.some(hint => lower.includes(hint));
-}
-
-function inferAssetKind(defType: string | null, key: string): AssetKind | null {
- const lower = key.toLowerCase();
- const matches = (hint: string) => lower === hint || lower.endsWith(hint) || lower.includes(`${hint}url`) || lower.includes(`${hint}src`);
- if (IMAGE_FIELD_HINTS.some(matches)) return 'image';
- if (VIDEO_FIELD_HINTS.some(matches)) return 'video';
- if (GENERIC_ASSET_HINTS.some(matches)) return 'media';
- if (lower === 'poster' || lower.endsWith('poster')) return 'image';
- if (lower === 'thumbnail' || lower.endsWith('thumbnail')) return 'image';
- if (lower === 'src') {
- if (defType === 'image' || defType === 'project' || defType === 'carousel') return 'image';
- if (defType === 'video') return 'video';
- }
- return null;
-}
-
-function deriveNumberBounds(field: z.ZodNumber) {
- const def: any = (field as unknown as { _def?: unknown })._def;
- const checks: Array<{ kind: string; value?: number }> = def?.checks ?? [];
- let min: number | undefined;
- let max: number | undefined;
- let step: number | undefined;
- let isInt = false;
- for (const check of checks) {
- if (check.kind === 'min' && typeof check.value === 'number') min = check.value;
- if (check.kind === 'max' && typeof check.value === 'number') max = check.value;
- if (check.kind === 'int') isInt = true;
- }
- if (isInt) step = 1;
- return { min, max, step };
-}
-
-function shouldUseTextareaField(defType: string | null, key: string) {
- const lower = key.toLowerCase();
- // If the key looks like a color (e.g. textColor) don't treat it as a textarea.
- if (lower.includes('color')) return false;
- // Match textarea hints as whole words or separated by non-alphanumerics to avoid
- // matching 'textColor' (which contains 'text' but is not a multiline field).
- for (const hint of TEXTAREA_FIELD_HINTS) {
- const re = new RegExp(`(^|[^a-z0-9])${hint}($|[^a-z0-9])`);
- if (re.test(lower)) return true;
- }
- if (defType === 'text' && lower === 'text') return true;
- return false;
-}
-
-function inferStringInputType(field: z.ZodTypeAny): 'text' | 'email' | 'url' {
- if (!(field instanceof z.ZodString)) return 'text';
- const def: any = (field as unknown as { _def?: unknown })._def;
- const checks: Array<{ kind?: string }> = def?.checks ?? [];
- if (checks.some(check => check.kind === 'email')) return 'email';
- if (checks.some(check => check.kind === 'url')) return 'url';
- return 'text';
-}
-
-export default function ModifyWidgetModal({
- item,
- onClose,
- onDelete,
- onRename,
- onBringToFront,
- onSendToBack,
- onBringForward,
- onSendBackward,
- onTogglePin,
- onToggleLock,
- onApplyProps,
-}: {
- item: GridItem;
- onClose: () => void;
- onDelete?: () => void;
- onRename: (title: string) => void;
- onBringToFront: () => void;
- onSendToBack: () => void;
- onBringForward: () => void;
- onSendBackward: () => void;
- onTogglePin: () => void;
- onToggleLock: () => void;
- onApplyProps: (props: any) => void;
-}) {
- useScrollLock(true);
- const { selectedProject } = useProjects();
- const { add: notify } = useNotifications();
- const widgetName = item.title || item.type || 'Widget';
- const [title, setTitle] = useState(item.title);
- const [propsText, setPropsText] = useState<string>(() => {
- try { return JSON.stringify(item.props ?? {}, null, 2); } catch { return "{}"; }
- });
- const [propsError, setPropsError] = useState<string | null>(null);
- const [zodSchema, setZodSchema] = useState<z.ZodObject<z.ZodRawShape> | null>(null);
- const [formValues, setFormValues] = useState<Record<string, unknown>>({});
- const [formErrors, setFormErrors] = useState<Record<string, string>>({});
- const [widgetDefaults, setWidgetDefaults] = useState<Record<string, unknown> | null>(null);
- const [defType, setDefType] = useState<string | null>(null);
- const [imageFileName, setImageFileName] = useState<string>("");
- const [videoFileName, setVideoFileName] = useState<string>("");
- const [posterFileName, setPosterFileName] = useState<string>("");
- const [carouselItems, setCarouselItems] = useState<CarouselEditorItem[]>([]);
- const [carouselError, setCarouselError] = useState<string | null>(null);
- const assets = useAssets();
- const imageAssetOptions = useMemo(() => assets.list.filter(asset => {
- if (asset.type?.startsWith('image/')) return true;
- const hasDimensions = typeof asset.width === 'number' && asset.width > 0 && typeof asset.height === 'number' && asset.height > 0;
- return hasDimensions;
- }), [assets.list]);
- React.useEffect(() => { console.info('ModifyWidgetModal: imageAssetOptionsCount=', imageAssetOptions.length, 'assetsListCount=', assets.list.length); }, [imageAssetOptions.length, assets.list.length]);
- const videoAssetOptions = useMemo(() => assets.list.filter(asset => asset.type?.startsWith('video/')), [assets.list]);
- const resolvedDefType = defType || item.type || null;
- const isCarousel = resolvedDefType === 'carousel';
- const isVideo = resolvedDefType === 'video';
- const videoShapeValue = ((typeof formValues.shape === 'string' ? formValues.shape : null) || 'rectangle') as 'rectangle' | 'rounded' | 'circle';
- const rawBorderWidth = formValues.borderWidth;
- const rawBorderRadius = formValues.borderRadius;
- const videoBorderWidthValue = typeof rawBorderWidth === 'number' && Number.isFinite(rawBorderWidth) ? rawBorderWidth : '';
- const videoBorderRadiusValue = typeof rawBorderRadius === 'number' && Number.isFinite(rawBorderRadius) ? rawBorderRadius : '';
- const videoBorderColorValue = (typeof formValues.borderColor === 'string' && /^#([0-9a-fA-F]{3}){1,2}$/.test(formValues.borderColor)) ? formValues.borderColor : '#e5e7eb';
- const videoBorderStyleValue = (typeof formValues.borderStyle === 'string' ? formValues.borderStyle : 'solid') as 'solid' | 'dashed' | 'dotted';
- // Carousel uses `radius` instead of `borderRadius` in its schema
- const carouselShapeValue = videoShapeValue;
- const rawCarouselRadius = formValues.radius;
- const carouselRadiusValue = typeof rawCarouselRadius === 'number' && Number.isFinite(rawCarouselRadius) ? rawCarouselRadius : '';
- // Derive navStyle from the current form values first, then fall back to the
- // original item props (in case the form hasn't been populated yet). This
- // ensures the UI shows the proper controls (e.g. textColor color picker)
- // when editing nav-link widgets.
- const navStyle = (defType === 'nav-link')
- ? String((formValues['style'] as string) ?? ((item.props as unknown as Record<string, unknown>)?.style as string) ?? 'link')
- : undefined;
- const videoBackgroundColorValue = typeof formValues.backgroundColor === 'string' ? formValues.backgroundColor : '';
- const videoBackgroundColorSwatch = HEX_COLOR_RE.test(videoBackgroundColorValue) ? videoBackgroundColorValue : '#ffffff';
- // Collapsible sections (persist across openings)
- const [compOpen, setCompOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_comp_props_open') === '1'; } catch { return false; }
- });
- const [widgetOpen, setWidgetOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_widget_props_open') === '1'; } catch { return false; }
- });
- function toggleCompOpen() {
- setCompOpen(prev => { const n = !prev; try { localStorage.setItem('py_comp_props_open', n ? '1' : '0'); } catch { /* noop */ } return n; });
- }
- function toggleWidgetOpen() {
- setWidgetOpen(prev => { const n = !prev; try { localStorage.setItem('py_widget_props_open', n ? '1' : '0'); } catch { /* noop */ } return n; });
- }
- function persistedToggle(key: string, setter: React.Dispatch<React.SetStateAction<boolean>>) {
- setter(prev => {
- const next = !prev;
- try { localStorage.setItem(key, next ? '1' : '0'); } catch { /* noop */ }
- return next;
- });
- }
- const [imageToolsOpen, setImageToolsOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_image_tools_open') !== '0'; } catch { return true; }
- });
- const [videoToolsOpen, setVideoToolsOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_video_tools_open') !== '0'; } catch { return true; }
- });
- const [carouselToolsOpen, setCarouselToolsOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_carousel_tools_open') !== '0'; } catch { return true; }
- });
- const [protectionOpen, setProtectionOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_widget_protection_open') !== '0'; } catch { return true; }
- });
- const [layerOpen, setLayerOpen] = useState<boolean>(() => {
- try { return localStorage.getItem('py_widget_layers_open') !== '0'; } catch { return true; }
- });
-
- // Keyboard helpers
- function handleEnterSubmitComp(e: React.KeyboardEvent) {
- if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey && !locked) {
- e.preventDefault();
- applyForm();
- }
- }
- function handleEnterSubmitAnywhere(e: React.KeyboardEvent) {
- if (locked || e.defaultPrevented) return;
- if (e.key !== 'Enter' || e.shiftKey || e.ctrlKey || e.metaKey) return;
- const target = e.target as HTMLElement | null;
- if (!target) return;
- if (target instanceof HTMLTextAreaElement) return;
- if (target instanceof HTMLInputElement) {
- const type = target.type?.toLowerCase();
- if (!type || !ENTER_SUBMIT_BLOCKED_TYPES.has(type)) {
- e.preventDefault();
- applyForm();
- }
- }
- }
- function handleCtrlEnterApplyJson(e: React.KeyboardEvent) {
+import { SchemaAssetField, SchemaNumberField, SchemaUrlField, type AssetKind } from "./settings/SchemaFields";
+import { ContactWidgetSettings } from "./settings/ContactWidgetSettings";
+import { ImageWidgetSettings } from "./settings/ImageWidgetSettings";
+import { LinkWidgetSettings } from "./settings/LinkWidgetSettings";
+import { NavLinkWidgetSettings } from "./settings/NavLinkWidgetSettings";
+import { TextWidgetSettings } from "./settings/TextWidgetSettings";
+import { VideoWidgetSettings } from "./settings/VideoWidgetSettings";
+import {
+ CONTACT_WIDGET_FIELD_KEYS,
+ deriveNumberBounds,
+ HEX_COLOR_RE,
+ IMAGE_WIDGET_FIELD_KEYS,
+ isLinkFontValue,
+ isLinkVariantValue,
+ isLinkWeightValue,
+ isNavLinkStyleValue,
+ isTextAlignValue,
+ isTextFontValue,
+ isTextFormatValue,
+ isTextVariantValue,
+ isTextWeightValue,
+ LINK_WIDGET_FIELD_KEYS,
+ LinkFontOption,
+ LinkVariantOption,
+ LinkWeightOption,
+ NAV_LINK_WIDGET_FIELD_KEYS,
+ NavLinkStyleOption,
+ TEXT_WIDGET_FIELD_KEYS,
+ TextAlignOption,
+ TextFontOption,
+ TextFormatOption,
+ TextVariantOption,
+ TextWeightOption,
+ VIDEO_WIDGET_FIELD_KEYS,
+} from "./settings/shared";
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter' && !locked) {
e.preventDefault();
applyProps();
@@ -481,29 +175,6 @@ export default function ModifyWidgetModal({
return () => { alive = false; };
}, [defType, formValues, assets]);
- useEffect(() => {
- let alive = true;
- async function go() {
- if (defType !== 'video') return;
- const src = formValues.src;
- if (typeof src === 'string' && src.startsWith('asset://')) {
- const hash = src.slice('asset://'.length);
- try { const meta = await assets.get(hash); if (alive) setVideoFileName(meta?.name || ''); } catch { /* ignore */ }
- } else {
- if (alive) setVideoFileName('');
- }
- const poster = formValues.poster;
- if (typeof poster === 'string' && poster.startsWith('asset://')) {
- const hash = poster.slice('asset://'.length);
- try { const meta = await assets.get(hash); if (alive) setPosterFileName(meta?.name || ''); } catch { /* ignore */ }
- } else {
- if (alive) setPosterFileName('');
- }
- }
- void go();
- return () => { alive = false; };
- }, [defType, formValues, assets]);
-
const locked = !!item.locked;
const pinned = !!item.pinned;
const linkRawUrl = defType === 'link' ? (typeof formValues.url === 'string' ? formValues.url : '') : '';
@@ -534,6 +205,7 @@ export default function ModifyWidgetModal({
const isTextWidget = resolvedDefType === 'text';
const isLinkWidget = resolvedDefType === 'link';
const isNavLinkWidget = resolvedDefType === 'nav-link';
+ const videoSchemaFields = new Map<string, z.ZodTypeAny>();
const textSchemaFields = new Map<string, z.ZodTypeAny>();
const linkSchemaFields = new Map<string, z.ZodTypeAny>();
const navLinkSchemaFields = new Map<string, z.ZodTypeAny>();
@@ -555,7 +227,8 @@ export default function ModifyWidgetModal({
navLinkSchemaFields.set(key, schema as z.ZodTypeAny);
continue;
}
- if (isVideo && (key === 'src' || key === 'poster' || VIDEO_APPEARANCE_FIELDS.has(key))) {
+ if (isVideo && VIDEO_WIDGET_FIELD_KEYS.has(key)) {
+ videoSchemaFields.set(key, schema as z.ZodTypeAny);
continue;
}
const bucket = isAppearanceField(defType, key) ? schemaFieldBuckets.appearance : schemaFieldBuckets.default;
@@ -838,6 +511,17 @@ export default function ModifyWidgetModal({
pages={navPages}
/>
) : null;
+ const videoWidgetSettingsNode = isVideo ? (
+ <VideoWidgetSettings
+ values={formValues}
+ errors={formErrors}
+ locked={locked}
+ setFieldValue={setFieldValue}
+ schemaFields={videoSchemaFields}
+ onCommitKeyDown={handleEnterSubmitComp}
+ widgetDefaults={widgetDefaults}
+ />
+ ) : null;
function applyProps() {
if (locked) return;
@@ -1721,6 +1405,7 @@ export default function ModifyWidgetModal({
{textWidgetSettingsNode}
{linkWidgetSettingsNode}
{navWidgetSettingsNode}
+ {videoWidgetSettingsNode}
{/* Zod-backed properties */}
{zodSchema && (!!defaultFieldNodes.length || !!appearanceFieldNodes.length || defType === 'link') && (
@@ -1907,1176 +1592,3 @@ export default function ModifyWidgetModal({
);
}
-type TextWidgetSettingsProps = {
- values: Record<string, unknown>;
- errors: Record<string, string>;
- locked: boolean;
- setFieldValue: (key: string, value: unknown) => void;
- schemaFields: Map<string, z.ZodTypeAny>;
- onCommitKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void;
- widgetDefaults: Record<string, unknown> | null;
-};
-
-function TextWidgetSettings({ values, errors, locked, setFieldValue, schemaFields, onCommitKeyDown, widgetDefaults }: TextWidgetSettingsProps) {
- type SectionKey = 'content' | 'typography' | 'accessibility';
- const [sectionsOpen, setSectionsOpen] = useState<Record<SectionKey, boolean>>({ content: true, typography: true, accessibility: true });
- const toggleSection = (key: SectionKey) => setSectionsOpen(prev => ({ ...prev, [key]: !prev[key] }));
- const getDefault = (key: string): unknown => {
- if (!widgetDefaults) return undefined;
- return widgetDefaults[key];
- };
- const textValue = typeof values.text === 'string'
- ? values.text
- : (typeof getDefault('text') === 'string' ? String(getDefault('text')) : '');
- const formatValue = isTextFormatValue(values.format)
- ? values.format
- : (isTextFormatValue(getDefault('format')) ? getDefault('format') as TextFormatOption : 'plain');
- const variantValue = isTextVariantValue(values.variant)
- ? values.variant
- : (isTextVariantValue(getDefault('variant')) ? getDefault('variant') as TextVariantOption : 'paragraph');
- const alignValue = isTextAlignValue(values.align)
- ? values.align
- : (isTextAlignValue(getDefault('align')) ? getDefault('align') as TextAlignOption : 'left');
- const fontValue = isTextFontValue(values.font)
- ? values.font
- : (isTextFontValue(getDefault('font')) ? getDefault('font') as TextFontOption : 'system');
- const weightValue = isTextWeightValue(values.weight)
- ? values.weight
- : (isTextWeightValue(getDefault('weight')) ? getDefault('weight') as TextWeightOption : 'normal');
- const italicDefault = typeof getDefault('italic') === 'boolean' ? Boolean(getDefault('italic')) : false;
- const italicValue = typeof values.italic === 'boolean' ? values.italic : italicDefault;
- const colorValue = typeof values.color === 'string' ? values.color : (typeof getDefault('color') === 'string' ? String(getDefault('color')) : '');
- const ariaLabelValue = typeof values.ariaLabel === 'string'
- ? values.ariaLabel
- : (typeof getDefault('ariaLabel') === 'string' ? String(getDefault('ariaLabel')) : '');
- const ariaDescriptionValue = typeof values.ariaDescription === 'string'
- ? values.ariaDescription
- : (typeof getDefault('ariaDescription') === 'string' ? String(getDefault('ariaDescription')) : '');
- const fontSizeField = schemaFields.get('fontSize');
- const fontSizeMeta = fontSizeField instanceof z.ZodNumber ? deriveNumberBounds(fontSizeField as z.ZodNumber) : undefined;
- const minFontSize = fontSizeMeta?.min ?? 8;
- const maxFontSize = fontSizeMeta?.max ?? 128;
- const fontSizeStep = fontSizeMeta?.step ?? 1;
- const defaultFontSize = getDefault('fontSize');
- const fallbackFontSize = typeof defaultFontSize === 'number' && Number.isFinite(defaultFontSize)
- ? Number(defaultFontSize)
- : Math.min(Math.max(16, minFontSize), maxFontSize);
- const customFontSize = typeof values.fontSize === 'number' && Number.isFinite(values.fontSize);
- const sliderFontSize = customFontSize ? Number(values.fontSize) : fallbackFontSize;
- const fontSizeInputValue = customFontSize ? Number(values.fontSize) : '';
- const colorSwatch = HEX_COLOR_RE.test(colorValue) ? colorValue : '#1f2937';
- const SectionCard = ({ sectionKey, title, icon, children }: { sectionKey: SectionKey; title: string; icon: React.ReactNode; children: React.ReactNode; }) => {
- const open = sectionsOpen[sectionKey];
- return (
- <div className="rounded-2xl border border-[color:var(--border)] bg-[color:var(--surface)]/95 shadow-sm">
- <button
- type="button"
- className="w-full flex items-center justify-between gap-2 px-4 py-3 text-left text-sm font-semibold text-[color:var(--fg)]"
- onClick={() => toggleSection(sectionKey)}
- aria-expanded={open}
- >
- <span className="flex items-center gap-2">
- {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
- <span className="flex items-center gap-2 text-[color:var(--fg)]">
- {icon}
- {title}
- </span>
- </span>
- <span className="text-[11px] text-[color:var(--fg-muted)]">{open ? 'Hide' : 'Show'}</span>
- </button>
- {open && (
- <div className="p-4 space-y-4 border-t border-[color:var(--border)] bg-[color:var(--surface)]">
- {children}
- </div>
- )}
- </div>
- );
- };
- const variantOptions: Array<{ value: TextVariantOption; label: string; description: string }> = [
- { value: 'paragraph', label: 'Paragraph', description: 'Standard body copy with inline formatting.' },
- { value: 'h2', label: 'Heading 2', description: 'Large section heading.' },
- { value: 'h3', label: 'Heading 3', description: 'Smaller heading for sub-sections.' },
- ];
- const alignmentOptions: Array<{ value: TextAlignOption; label: string; icon: React.ReactNode }> = [
- { value: 'left', label: 'Left align', icon: <AlignLeft size={14} /> },
- { value: 'center', label: 'Center align', icon: <AlignCenter size={14} /> },
- { value: 'right', label: 'Right align', icon: <AlignRight size={14} /> },
- ];
- const fontOptions: Array<{ value: TextFontOption; label: string; sample: string }> = [
- { value: 'system', label: 'System', sample: 'Aa' },
- { value: 'serif', label: 'Serif', sample: 'Aa' },
- { value: 'mono', label: 'Mono', sample: '{ }' },
- ];
- const formatHelper = formatValue === 'markdown'
- ? 'Use **bold**, _italic_, lists, links, and more with GitHub-flavored Markdown.'
- : 'Best for simple paragraphs. Switch to Markdown for rich formatting.';
-
- return (
- <div className="space-y-4">
- <SectionCard sectionKey="content" title="Text content" icon={<Type size={14} />}>
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Text *</label>
- <textarea
- className="input w-full min-h-[6rem]"
- value={textValue}
- onChange={(e) => setFieldValue('text', e.target.value)}
- disabled={locked}
- />
- <div className="text-[10px] text-[color:var(--fg-muted)] mt-1 flex items-center justify-between">
- <span>{textValue.length} characters</span>
- <span>{formatValue === 'markdown' ? 'Markdown enabled' : 'Plain text'}</span>
- </div>
- {errors.text && <div className="text-xs text-red-500 mt-1">{errors.text}</div>}
- </div>
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Format</label>
- <div className="flex flex-wrap gap-2">
- {TEXT_FORMATS.map((fmt) => (
- <button
- key={fmt}
- type="button"
- className={`flex-1 min-w-[8rem] px-3 py-1.5 rounded border text-xs font-semibold transition-colors duration-150 ${formatValue === fmt ? 'bg-[color:var(--accent)]/20 border-[color:var(--accent)] text-[color:var(--accent)]' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] bg-[color:var(--surface)]/70 hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('format', fmt)}
- disabled={locked}
- >
- {fmt === 'plain' ? 'Plain text' : 'Markdown'}
- </button>
- ))}
- </div>
- <div className="text-[10px] text-[color:var(--fg-muted)] mt-1">{formatHelper}</div>
- </div>
- </SectionCard>
-
- <SectionCard sectionKey="typography" title="Typography & layout" icon={<AlignLeft size={14} />}>
- <div className="space-y-2">
- <label className="block text-[color:var(--fg-muted)] mb-1">Variant</label>
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
- {variantOptions.map((option) => (
- <button
- key={option.value}
- type="button"
- className={`text-left px-3 py-2 rounded border transition-colors duration-150 ${variantValue === option.value ? 'border-[color:var(--accent)] bg-[color:var(--accent)]/15 text-[color:var(--accent)] shadow-sm' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('variant', option.value)}
- disabled={locked}
- >
- <div className="text-sm font-semibold">{option.label}</div>
- <div className="text-[11px] text-[color:var(--fg-muted)]/90">{option.description}</div>
- </button>
- ))}
- </div>
- {errors.variant && <div className="text-xs text-red-500">{errors.variant}</div>}
- </div>
-
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Alignment</label>
- <div className="flex flex-wrap gap-2">
- {alignmentOptions.map((option) => (
- <button
- key={option.value}
- type="button"
- className={`flex-1 min-w-[5rem] px-3 py-1.5 rounded border text-xs font-semibold transition-colors duration-150 ${alignValue === option.value ? 'bg-[color:var(--accent)]/25 border-[color:var(--accent)] text-[color:var(--accent)] shadow-sm' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] bg-[color:var(--surface)]/70 hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('align', option.value)}
- disabled={locked}
- title={option.label}
- >
- <div className="flex items-center justify-center gap-1">
- {option.icon}
- <span className="text-[11px]">{option.label.split(' ')[0]}</span>
- </div>
- </button>
- ))}
- </div>
- {errors.align && <div className="text-xs text-red-500 mt-1">{errors.align}</div>}
- </div>
-
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Font family</label>
- <div className="rounded-xl border border-[color:var(--accent)] bg-[color:var(--accent)]/12 p-3 shadow-sm">
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-white">
- {fontOptions.map((option) => (
- <button
- key={option.value}
- type="button"
- className={`px-3 py-2 rounded-lg border text-left text-sm font-semibold transition-colors duration-150 ${fontValue === option.value ? 'bg-[color:var(--accent)] text-white border-[color:var(--accent)] shadow-md' : 'bg-white/5 border-white/30 text-white/80 hover:bg-[color:var(--accent)]/80 hover:text-white'}`}
- onClick={() => setFieldValue('font', option.value)}
- disabled={locked}
- >
- <div className="flex items-center justify-between">
- <span>{option.label}</span>
- <span className="text-lg font-semibold">{option.sample}</span>
- </div>
- </button>
- ))}
- </div>
- </div>
- {errors.font && <div className="text-xs text-red-500 mt-1">{errors.font}</div>}
- </div>
-
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Weight</label>
- <div className="flex gap-2">
- {TEXT_WEIGHTS.map((weight) => (
- <button
- key={weight}
- type="button"
- className={`flex-1 px-3 py-1.5 rounded border text-xs font-semibold transition-colors duration-150 ${weightValue === weight ? 'bg-[color:var(--accent)]/20 border-[color:var(--accent)] text-[color:var(--accent)] shadow-sm' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('weight', weight)}
- disabled={locked}
- >
- <span className="flex items-center gap-1">
- <BoldIcon size={14} />
- {weight === 'bold' ? 'Bold' : 'Normal'}
- </span>
- </button>
- ))}
- </div>
- {errors.weight && <div className="text-xs text-red-500 mt-1">{errors.weight}</div>}
- </div>
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Italic</label>
- <button
- type="button"
- className={`w-full px-3 py-1.5 rounded border text-xs font-semibold transition-colors duration-150 ${italicValue ? 'bg-[color:var(--accent)]/20 border-[color:var(--accent)] text-[color:var(--accent)] shadow-sm' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('italic', !italicValue)}
- disabled={locked}
- >
- <span className="flex items-center gap-2 justify-center">
- <ItalicIcon size={14} />
- {italicValue ? 'Enabled' : 'Disabled'}
- </span>
- </button>
- {errors.italic && <div className="text-xs text-red-500 mt-1">{errors.italic}</div>}
- </div>
- </div>
-
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Font size</label>
- <input
- type="range"
- className="w-full accent-[color:var(--accent)]"
- min={minFontSize}
- max={maxFontSize}
- step={fontSizeStep}
- value={sliderFontSize}
- onChange={(e) => setFieldValue('fontSize', Number(e.target.value))}
- disabled={locked}
- />
- <div className="flex flex-wrap items-center gap-2 mt-2">
- <input
- className="input w-24"
- type="number"
- min={minFontSize}
- max={maxFontSize}
- step={fontSizeStep}
- value={fontSizeInputValue}
- placeholder={`${minFontSize}-${maxFontSize}`}
- onChange={(e) => {
- const raw = e.target.value;
- setFieldValue('fontSize', raw === '' ? undefined : Number(raw));
- }}
- onKeyDown={onCommitKeyDown}
- disabled={locked}
- />
- <button
- type="button"
- className="px-3 py-1.5 rounded border border-[color:var(--border)] text-xs font-semibold transition-colors duration-150 hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]"
- onClick={() => setFieldValue('fontSize', undefined)}
- disabled={locked || !customFontSize}
- >
- Auto
- </button>
- <div className="text-[11px] text-[color:var(--fg-muted)]">{customFontSize ? `${fontSizeInputValue}px` : 'Inherit theme size'}</div>
- </div>
- {errors.fontSize && <div className="text-xs text-red-500 mt-1">{errors.fontSize}</div>}
- </div>
-
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Text color</label>
- <div className="flex flex-wrap items-center gap-2">
- <input
- type="color"
- className="rounded border border-[color:var(--border)] bg-[color:var(--muted)]/40 h-8 w-12 cursor-pointer"
- value={colorSwatch}
- onChange={(e) => setFieldValue('color', e.target.value)}
- disabled={locked}
- aria-label="Pick text color"
- />
- <input
- className="input flex-1 font-mono text-xs"
- value={colorValue}
- placeholder="Inherit"
- onChange={(e) => setFieldValue('color', e.target.value || undefined)}
- onKeyDown={onCommitKeyDown}
- disabled={locked}
- />
- <button
- type="button"
- className="px-2 py-1 rounded border border-[color:var(--border)] text-[10px] font-semibold transition-colors duration-150 hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]"
- onClick={() => setFieldValue('color', undefined)}
- disabled={locked || !colorValue}
- >
- Reset
- </button>
- </div>
- <div className="text-[10px] text-[color:var(--fg-muted)] mt-1">Leave blank to inherit the theme color or use CSS variables like var(--fg).</div>
- {errors.color && <div className="text-xs text-red-500 mt-1">{errors.color}</div>}
- </div>
- </SectionCard>
-
- <SectionCard sectionKey="accessibility" title="Accessibility" icon={<Unlock size={14} />}>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Aria label</label>
- <input
- className="input w-full"
- value={ariaLabelValue}
- onChange={(e) => setFieldValue('ariaLabel', e.target.value || undefined)}
- onKeyDown={onCommitKeyDown}
- placeholder="Optional short label"
- disabled={locked}
- />
- <div className="text-[10px] text-[color:var(--fg-muted)] mt-1">Helps screen readers describe the block when text is decorative.</div>
- {errors.ariaLabel && <div className="text-xs text-red-500 mt-1">{errors.ariaLabel}</div>}
- </div>
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Aria description</label>
- <textarea
- className="input w-full min-h-[4rem]"
- value={ariaDescriptionValue}
- onChange={(e) => setFieldValue('ariaDescription', e.target.value || undefined)}
- disabled={locked}
- />
- <div className="text-[10px] text-[color:var(--fg-muted)] mt-1">Add extra context that is not visible on screen.</div>
- {errors.ariaDescription && <div className="text-xs text-red-500 mt-1">{errors.ariaDescription}</div>}
- </div>
- </div>
- </SectionCard>
- </div>
- );
-}
-
-type LinkWidgetSettingsProps = {
- values: Record<string, unknown>;
- errors: Record<string, string>;
- locked: boolean;
- setFieldValue: (key: string, value: unknown) => void;
- schemaFields: Map<string, z.ZodTypeAny>;
- onCommitKeyDown: (event: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
- widgetDefaults: Record<string, unknown> | null;
- rawUrl: string;
- fieldError: string | null;
-};
-
-function LinkWidgetSettings({ values, errors, locked, setFieldValue, schemaFields, onCommitKeyDown, widgetDefaults, rawUrl, fieldError }: LinkWidgetSettingsProps) {
- type SectionKey = 'destination' | 'appearance' | 'icons';
- const [sectionsOpen, setSectionsOpen] = useState<Record<SectionKey, boolean>>({ destination: true, appearance: true, icons: true });
- const toggleSection = (key: SectionKey) => setSectionsOpen(prev => ({ ...prev, [key]: !prev[key] }));
- const getDefault = (key: string): unknown => (widgetDefaults ? widgetDefaults[key] : undefined);
- const urlValue = typeof values.url === 'string'
- ? values.url
- : (typeof getDefault('url') === 'string' ? String(getDefault('url')) : '');
- const labelValue = typeof values.label === 'string'
- ? values.label
- : (typeof getDefault('label') === 'string' ? String(getDefault('label')) : '');
- const variantValue = isLinkVariantValue(values.variant)
- ? values.variant
- : (isLinkVariantValue(getDefault('variant')) ? getDefault('variant') as LinkVariantOption : 'button');
- const fontValue = isLinkFontValue(values.font)
- ? values.font as LinkFontOption
- : (isLinkFontValue(getDefault('font')) ? getDefault('font') as LinkFontOption : 'system');
- const weightValue = isLinkWeightValue(values.weight)
- ? values.weight as LinkWeightOption
- : (isLinkWeightValue(getDefault('weight')) ? getDefault('weight') as LinkWeightOption : 'bold');
- const italicDefault = typeof getDefault('italic') === 'boolean' ? Boolean(getDefault('italic')) : false;
- const italicValue = typeof values.italic === 'boolean' ? values.italic : italicDefault;
- const iconLeftValue = typeof values.iconLeft === 'string' ? values.iconLeft : '';
- const iconRightValue = typeof values.iconRight === 'string' ? values.iconRight : '';
- const ariaLabelValue = typeof values.ariaLabel === 'string'
- ? values.ariaLabel
- : (typeof getDefault('ariaLabel') === 'string' ? String(getDefault('ariaLabel')) : '');
- const ariaDescriptionValue = typeof values.ariaDescription === 'string'
- ? values.ariaDescription
- : (typeof getDefault('ariaDescription') === 'string' ? String(getDefault('ariaDescription')) : '');
- const fontSizeField = schemaFields.get('fontSize');
- const fontSizeMeta = fontSizeField instanceof z.ZodNumber ? deriveNumberBounds(fontSizeField as z.ZodNumber) : undefined;
- const minFontSize = fontSizeMeta?.min ?? 8;
- const maxFontSize = fontSizeMeta?.max ?? 128;
- const fontSizeStep = fontSizeMeta?.step ?? 1;
- const defaultFontSize = widgetDefaults && typeof widgetDefaults.fontSize === 'number' ? widgetDefaults.fontSize : 16;
- const customFontSize = typeof values.fontSize === 'number' && Number.isFinite(values.fontSize);
- const sliderFontSize = customFontSize ? Number(values.fontSize) : defaultFontSize;
- const fontSizeInputValue = customFontSize ? Number(values.fontSize) : '';
- const SectionCard = ({ sectionKey, title, icon, children }: { sectionKey: SectionKey; title: string; icon: React.ReactNode; children: React.ReactNode; }) => {
- const open = sectionsOpen[sectionKey];
- return (
- <div className="rounded-2xl border border-[color:var(--border)] bg-[color:var(--surface)]/95 shadow-sm">
- <button
- type="button"
- className="w-full flex items-center justify-between gap-2 px-4 py-3 text-left text-sm font-semibold"
- onClick={() => toggleSection(sectionKey)}
- aria-expanded={open}
- >
- <span className="flex items-center gap-2 text-[color:var(--fg)]">
- {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
- <span className="flex items-center gap-2 text-[color:var(--fg)]">
- {icon}
- {title}
- </span>
- </span>
- <span className="text-[11px] text-[color:var(--fg-muted)]">{open ? 'Hide' : 'Show'}</span>
- </button>
- {open && (
- <div className="p-4 space-y-4 border-t border-[color:var(--border)] bg-[color:var(--surface)]">
- {children}
- </div>
- )}
- </div>
- );
- };
- const variantOptions: Array<{ value: LinkVariantOption; label: string; description: string }> = [
- { value: 'button', label: 'Button', description: 'Rounded pill-style button with accent fill.' },
- { value: 'text', label: 'Text link', description: 'Inline link that inherits theme accent.' },
- { value: 'card', label: 'Card', description: 'Full-width card with border and metadata.' },
- ];
- const fontOptions: Array<{ value: LinkFontOption; label: string; sample: string }> = [
- { value: 'system', label: 'System', sample: 'Aa' },
- { value: 'serif', label: 'Serif', sample: 'Aa' },
- { value: 'mono', label: 'Mono', sample: '{ }' },
- ];
- const iconCharLimit = 24;
- return (
- <div className="space-y-4">
- <SectionCard sectionKey="destination" title="Destination & label" icon={<LinkIcon size={14} />}>
- <div className="space-y-2">
- <label className="block text-[color:var(--fg-muted)] mb-1">URL *</label>
- <SchemaUrlField
- value={urlValue}
- disabled={locked}
- onChange={(next) => setFieldValue('url', next ?? '')}
- onKeyDown={onCommitKeyDown}
- />
- <div className="text-[10px] text-[color:var(--fg-muted)]">Supports {ALLOWED_HTTP_SCHEME_LABEL} links. Missing protocol defaults to https://.</div>
- {errors.url && <div className="text-xs text-red-500">{errors.url}</div>}
- </div>
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Label *</label>
- <input
- className="input w-full"
- value={labelValue}
- maxLength={80}
- onChange={(e) => setFieldValue('label', e.target.value)}
- onKeyDown={onCommitKeyDown}
- disabled={locked}
- />
- <div className="text-[10px] text-[color:var(--fg-muted)] flex justify-between mt-1">
- <span>{labelValue.length}/80 characters</span>
- <span>Shown to visitors</span>
- </div>
- {errors.label && <div className="text-xs text-red-500 mt-1">{errors.label}</div>}
- </div>
- <LinkPreviewPanel rawUrl={rawUrl} fieldError={fieldError} disabled={locked} />
- </SectionCard>
-
- <SectionCard sectionKey="appearance" title="Appearance" icon={<Palette size={14} />}>
- <div className="space-y-2">
- <label className="block text-[color:var(--fg-muted)] mb-1">Variant</label>
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
- {variantOptions.map((option) => (
- <button
- key={option.value}
- type="button"
- className={`text-left px-3 py-2 rounded border transition-colors duration-150 ${variantValue === option.value ? 'border-[color:var(--accent)] bg-[color:var(--accent)]/15 text-[color:var(--accent)] shadow-sm' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('variant', option.value)}
- disabled={locked}
- >
- <div className="text-sm font-semibold">{option.label}</div>
- <div className="text-[11px] text-[color:var(--fg-muted)]/90">{option.description}</div>
- </button>
- ))}
- </div>
- {errors.variant && <div className="text-xs text-red-500">{errors.variant}</div>}
- </div>
-
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Font</label>
- <div className="rounded-xl border border-[color:var(--accent)] bg-[color:var(--accent)]/12 p-3 shadow-sm">
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-white">
- {fontOptions.map((option) => (
- <button
- key={option.value}
- type="button"
- className={`px-3 py-2 rounded-lg border text-left text-sm font-semibold transition-colors duration-150 ${fontValue === option.value ? 'bg-[color:var(--accent)] text-white border-[color:var(--accent)] shadow-md' : 'bg-white/5 border-white/30 text-white/80 hover:bg-[color:var(--accent)]/80 hover:text-white'}`}
- onClick={() => setFieldValue('font', option.value)}
- disabled={locked}
- >
- <div className="flex items-center justify-between">
- <span>{option.label}</span>
- <span className="text-lg font-semibold">{option.sample}</span>
- </div>
- </button>
- ))}
- </div>
- </div>
- {errors.font && <div className="text-xs text-red-500 mt-1">{errors.font}</div>}
- </div>
-
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div>
- <label className="block text-[color:var(--fg-muted)] mb-1">Weight</label>
- <div className="flex gap-2">
- {TEXT_WEIGHTS.map((weight) => (
- <button
- key={weight}
- type="button"
- className={`flex-1 px-3 py-1.5 rounded border text-xs font-semibold transition-colors duration-150 ${weightValue === weight ? 'bg-[color:var(--accent)]/20 border-[color:var(--accent)] text-[color:var(--accent)] shadow-sm' : 'border-[color:var(--border)] text-[color:var(--fg-muted)] hover:border-[color:var(--accent)] hover:text-[color:var(--accent)]'}`}
- onClick={() => setFieldValue('weight', weight)}
- disabled={locked}
- >
- <span className="flex items-center gap-1">
- <BoldIcon size={14} />
- {weight === 'bold' ? 'Bold' : 'Normal'}
- </span>
- </button>
- ))}
- </div>
- {errors.weight && <div className="text-xs text-red-500 mt-1">{errors.weight}</div>}
- </div>