@hyperframes/studio 0.5.0-alpha.9 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/assets/hyperframes-player-CoI5h1xv.js +353 -0
  2. package/dist/assets/index-BKjcNNNd.css +1 -0
  3. package/dist/assets/index-CqiisJmo.js +93 -0
  4. package/dist/index.html +2 -2
  5. package/package.json +4 -4
  6. package/src/App.tsx +208 -1438
  7. package/src/captions/generator.test.ts +19 -0
  8. package/src/captions/generator.ts +9 -2
  9. package/src/captions/hooks/useCaptionSync.ts +6 -1
  10. package/src/captions/parser.test.ts +14 -0
  11. package/src/captions/parser.ts +1 -0
  12. package/src/components/LintModal.tsx +4 -3
  13. package/src/components/editor/PropertyPanel.tsx +206 -2466
  14. package/src/components/nle/NLELayout.tsx +47 -17
  15. package/src/components/nle/NLEPreview.tsx +5 -50
  16. package/src/components/sidebar/AssetsTab.tsx +4 -3
  17. package/src/components/sidebar/CompositionsTab.test.ts +1 -16
  18. package/src/components/sidebar/CompositionsTab.tsx +45 -117
  19. package/src/components/sidebar/LeftSidebar.tsx +55 -34
  20. package/src/components/ui/HyperframesLoader.tsx +104 -0
  21. package/src/components/ui/index.ts +2 -0
  22. package/src/icons/SystemIcons.tsx +2 -0
  23. package/src/player/components/CompositionThumbnail.tsx +10 -42
  24. package/src/player/components/EditModal.tsx +20 -5
  25. package/src/player/components/Player.tsx +129 -28
  26. package/src/player/components/PlayerControls.tsx +3 -44
  27. package/src/player/components/Timeline.test.ts +0 -12
  28. package/src/player/components/Timeline.tsx +25 -52
  29. package/src/player/components/TimelineClip.tsx +9 -21
  30. package/src/player/components/timelineEditing.test.ts +4 -2
  31. package/src/player/components/timelineEditing.ts +3 -1
  32. package/src/player/components/timelineTheme.test.ts +19 -0
  33. package/src/player/components/timelineTheme.ts +8 -4
  34. package/src/player/hooks/useTimelinePlayer.test.ts +160 -21
  35. package/src/player/hooks/useTimelinePlayer.ts +206 -93
  36. package/src/player/lib/time.test.ts +11 -1
  37. package/src/player/lib/time.ts +6 -0
  38. package/src/player/store/playerStore.ts +1 -0
  39. package/src/styles/studio.css +112 -0
  40. package/src/utils/frameCapture.test.ts +26 -0
  41. package/src/utils/frameCapture.ts +40 -0
  42. package/src/utils/mediaTypes.ts +1 -1
  43. package/src/utils/projectRouting.test.ts +87 -0
  44. package/src/utils/projectRouting.ts +27 -0
  45. package/src/utils/sourcePatcher.test.ts +1 -128
  46. package/src/utils/sourcePatcher.ts +18 -130
  47. package/src/utils/timelineAssetDrop.test.ts +11 -31
  48. package/src/utils/timelineAssetDrop.ts +2 -22
  49. package/dist/assets/hyperframes-player-vibA20NC.js +0 -198
  50. package/dist/assets/index-DKaNgV2Z.css +0 -1
  51. package/dist/assets/index-peNJzL-4.js +0 -105
  52. package/src/components/editor/DomEditOverlay.tsx +0 -445
  53. package/src/components/editor/colorValue.test.ts +0 -82
  54. package/src/components/editor/colorValue.ts +0 -175
  55. package/src/components/editor/domEditing.test.ts +0 -537
  56. package/src/components/editor/domEditing.ts +0 -762
  57. package/src/components/editor/floatingPanel.test.ts +0 -34
  58. package/src/components/editor/floatingPanel.ts +0 -54
  59. package/src/components/editor/fontAssets.ts +0 -32
  60. package/src/components/editor/fontCatalog.ts +0 -126
  61. package/src/components/editor/gradientValue.test.ts +0 -89
  62. package/src/components/editor/gradientValue.ts +0 -445
  63. package/src/player/components/CompositionThumbnail.test.ts +0 -19
  64. package/src/utils/clipboard.test.ts +0 -88
  65. package/src/utils/clipboard.ts +0 -57
@@ -1,2532 +1,272 @@
1
- import {
2
- memo,
3
- useCallback,
4
- useEffect,
5
- useLayoutEffect,
6
- useMemo,
7
- useRef,
8
- useState,
9
- type ReactNode,
10
- } from "react";
11
- import { createPortal } from "react-dom";
12
- import {
13
- Eye,
14
- Layers,
15
- MessageSquare,
16
- Move,
17
- Palette,
18
- Plus,
19
- RotateCcw,
20
- Settings,
21
- Type,
22
- X,
23
- } from "../../icons/SystemIcons";
24
- import {
25
- formatCssColor,
26
- hsvToRgb,
27
- parseCssColor,
28
- rgbToHsv,
29
- toColorPickerValue,
30
- toHexColor,
31
- type ParsedColor,
32
- } from "./colorValue";
33
- import {
34
- buildDefaultGradientModel,
35
- insertGradientStop,
36
- parseGradient,
37
- serializeGradient,
38
- type GradientModel,
39
- } from "./gradientValue";
40
- import { isTextEditableSelection, type DomEditSelection } from "./domEditing";
41
- import {
42
- COMMON_LOCAL_FONT_FAMILIES,
43
- googleFontStylesheetUrl,
44
- POPULAR_GOOGLE_FONT_FAMILIES,
45
- } from "./fontCatalog";
46
- import { fontFamilyFromAssetPath, importedFontFaceCss, type ImportedFontAsset } from "./fontAssets";
47
- import { resolveFloatingPanelPosition, type FloatingPosition } from "./floatingPanel";
48
- import { IMAGE_EXT } from "../../utils/mediaTypes";
1
+ import { memo } from "react";
2
+ import { X, MousePointer, Move, Type, Palette, Clock, Eye } from "../../icons/SystemIcons";
3
+ import { Button, IconButton } from "../ui";
4
+ import type { PickedElement } from "../../hooks/useElementPicker";
49
5
 
50
6
  interface PropertyPanelProps {
51
- projectId: string;
52
- assets: string[];
53
- element: DomEditSelection | null;
54
- copiedAgentPrompt: boolean;
55
- onClearSelection: () => void;
7
+ element: PickedElement | null;
8
+ isPickMode: boolean;
9
+ onEnablePick: () => void;
10
+ onDisablePick: () => void;
11
+ onClearPick: () => void;
56
12
  onSetStyle: (prop: string, value: string) => void;
57
- onSetText: (value: string, fieldKey?: string) => void;
58
- onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void;
59
- onAddTextField: (afterFieldKey?: string) => string | Promise<string | null> | null;
60
- onRemoveTextField: (fieldKey: string) => void;
61
- onDetachFromLayout: () => void;
62
- onAskAgent: () => void;
63
- onCopyAgentInstruction: (instruction: string) => void | Promise<void>;
64
- onImportAssets?: (files: FileList) => Promise<string[]>;
65
- fontAssets?: ImportedFontAsset[];
66
- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;
67
- allowLayoutDetach?: boolean;
13
+ onSetDataAttr: (attr: string, value: string) => void;
14
+ onSetText?: (text: string) => void;
68
15
  }
69
16
 
70
- const FIELD =
71
- "min-w-0 rounded-xl border border-neutral-800 bg-neutral-900/95 px-3 py-2 text-neutral-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)] transition-colors focus-within:border-neutral-600";
72
- const LABEL = "text-[11px] font-medium uppercase tracking-[0.18em] text-neutral-500";
73
- const RESPONSIVE_GRID = "grid grid-cols-[repeat(auto-fit,minmax(118px,1fr))] gap-3";
74
- const EMPTY_STYLES: Record<string, string> = {};
75
- const GENERIC_FONT_FAMILIES = new Set([
76
- "inherit",
77
- "initial",
78
- "revert",
79
- "revert-layer",
80
- "serif",
81
- "sans-serif",
82
- "monospace",
83
- "cursive",
84
- "fantasy",
85
- "system-ui",
86
- "ui-sans-serif",
87
- "ui-serif",
88
- "ui-monospace",
89
- "ui-rounded",
90
- "emoji",
91
- "math",
92
- "fangsong",
93
- ]);
94
- const DEFAULT_FONT_FAMILIES = [
95
- ...COMMON_LOCAL_FONT_FAMILIES,
96
- "Inter",
97
- "system-ui",
98
- "sans-serif",
99
- "serif",
100
- "monospace",
101
- ];
102
-
103
- interface LocalFontData {
104
- family: string;
105
- fullName?: string;
106
- postscriptName?: string;
107
- style?: string;
108
- blob?: () => Promise<Blob>;
109
- }
110
-
111
- type FontSource = "Current" | "Document" | "Imported" | "Local" | "Google" | "System";
112
-
113
- interface FontOption {
114
- family: string;
115
- source: FontSource;
116
- }
117
-
118
- const COLOR_PICKER_SIZE = { width: 292, height: 386 };
119
-
120
- function buildMakeMovableAgentInstruction(reason: string): string {
121
- return [
122
- "Make this selected HyperFrames element movable in Studio.",
123
- `Studio blocked direct move/resize because: ${reason}`,
124
- "Refactor only this element safely.",
125
- "Preserve its current visual position, timing, and sibling layout intent where possible.",
126
- "If it is transform-driven, replace transform-based positioning with absolute pixel geometry.",
127
- "If layout flow owns it, detach conservatively with position: absolute, px left/top/width/height, and margin: 0.",
128
- ].join(" ");
129
- }
130
-
131
- function colorFromCss(value: string): ParsedColor {
132
- return parseCssColor(value) ?? { red: 0, green: 0, blue: 0, alpha: 1 };
133
- }
134
-
135
- declare global {
136
- interface Window {
137
- queryLocalFonts?: () => Promise<LocalFontData[]>;
138
- }
139
- }
140
-
141
- function sanitizeFontFilePart(value: string): string {
142
- return value
143
- .replace(/[^\w .-]+/g, " ")
144
- .replace(/\s+/g, " ")
145
- .trim();
146
- }
147
-
148
- function localFontSortScore(font: LocalFontData): number {
149
- const style = font.style?.toLowerCase() ?? "";
150
- const fullName = font.fullName?.toLowerCase() ?? "";
151
- if (style === "regular" || fullName.endsWith(" regular")) return 0;
152
- if (style === "normal" || fullName.endsWith(" normal")) return 1;
153
- if (style === "medium" || fullName.endsWith(" medium")) return 2;
154
- return 3;
155
- }
156
-
157
- function parseNumericValue(value: string | undefined): number | null {
158
- if (!value) return null;
159
- const parsed = Number.parseFloat(value);
160
- return Number.isFinite(parsed) ? parsed : null;
161
- }
162
-
163
- function formatNumericValue(value: number): string {
164
- const rounded = Math.round(value * 100) / 100;
165
- return Number.isInteger(rounded)
166
- ? `${rounded}`
167
- : rounded.toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
168
- }
169
-
170
- interface ParsedNumericToken {
171
- value: number;
172
- unit: string;
173
- }
174
-
175
- function parseNumericToken(value: string | undefined): ParsedNumericToken | null {
176
- if (!value) return null;
177
- const match = value.trim().match(/^(-?\d+(?:\.\d+)?)([a-z%]*)$/i);
178
- if (!match) return null;
179
- const parsed = Number.parseFloat(match[1]);
180
- if (!Number.isFinite(parsed)) return null;
181
- return {
182
- value: parsed,
183
- unit: match[2] ?? "",
184
- };
185
- }
186
-
187
- function adjustNumericToken(
188
- value: string,
189
- direction: 1 | -1,
190
- modifiers?: { shiftKey?: boolean; altKey?: boolean },
191
- ): string | null {
192
- const token = parseNumericToken(value);
193
- if (!token) return null;
194
-
195
- const baseStep = modifiers?.altKey ? 0.1 : modifiers?.shiftKey ? 10 : 1;
196
- const nextValue = token.value + baseStep * direction;
197
- return `${formatNumericValue(nextValue)}${token.unit}`;
198
- }
199
-
200
- function formatColorToken(value: string): string {
201
- const parsed = parseCssColor(value);
202
- if (!parsed) return value;
203
- const hex = toColorPickerValue(value).replace(/^#/, "").toUpperCase();
204
- return `${hex} / ${Math.round(parsed.alpha * 100)}%`;
205
- }
206
-
207
- function extractBackgroundImageUrl(value: string | undefined): string {
208
- if (!value) return "";
209
- const lowerValue = value.toLowerCase();
210
- const urlStart = lowerValue.indexOf("url(");
211
- if (urlStart < 0) return "";
212
-
213
- let index = urlStart + 4;
214
- while (
215
- index < value.length &&
216
- (value[index] === " " ||
217
- value[index] === "\n" ||
218
- value[index] === "\r" ||
219
- value[index] === "\t" ||
220
- value[index] === "\f")
221
- ) {
222
- index += 1;
223
- }
224
-
225
- const quote = value[index] === '"' || value[index] === "'" ? value[index] : null;
226
- if (quote) {
227
- index += 1;
228
- const endQuote = value.indexOf(quote, index);
229
- return endQuote >= index ? value.slice(index, endQuote) : "";
230
- }
231
-
232
- const endParen = value.indexOf(")", index);
233
- if (endParen < index) return "";
234
- return value.slice(index, endParen).trim();
235
- }
236
-
237
- function normalizeProjectPath(value: string): string {
238
- const trimmed = value.trim();
239
- const maybeUrl = /^[a-z]+:\/\//i.test(trimmed) ? new URL(trimmed).pathname : trimmed;
240
- return decodeURIComponent(maybeUrl)
241
- .replace(/\\/g, "/")
242
- .replace(/^\.?\//, "");
243
- }
244
-
245
- function toRelativeProjectAssetPath(sourceFile: string, assetPath: string): string {
246
- const fromParts = normalizeProjectPath(sourceFile).split("/").filter(Boolean);
247
- const targetParts = normalizeProjectPath(assetPath).split("/").filter(Boolean);
248
-
249
- fromParts.pop();
250
-
251
- while (fromParts.length > 0 && targetParts.length > 0 && fromParts[0] === targetParts[0]) {
252
- fromParts.shift();
253
- targetParts.shift();
254
- }
255
-
256
- return [...fromParts.map(() => ".."), ...targetParts].join("/") || assetPath;
257
- }
258
-
259
- function toProjectRootAssetPath(assetPath: string): string {
260
- return normalizeProjectPath(assetPath);
261
- }
262
-
263
- function resolveSelectedAsset(
264
- imageUrl: string,
265
- sourceFile: string,
266
- assets: string[],
267
- ): string | null {
268
- const normalizedUrl = normalizeProjectPath(imageUrl);
269
- if (!normalizedUrl) return null;
270
-
271
- for (const asset of assets) {
272
- const normalizedAsset = normalizeProjectPath(asset);
273
- const relativeAsset = toRelativeProjectAssetPath(sourceFile, asset);
274
- if (
275
- normalizedUrl === normalizedAsset ||
276
- normalizedUrl === relativeAsset ||
277
- normalizedUrl.endsWith(`/${normalizedAsset}`) ||
278
- normalizedUrl.endsWith(`/${relativeAsset}`)
279
- ) {
280
- return asset;
281
- }
282
- }
283
-
284
- return null;
285
- }
286
-
287
- function collectSelectionColors(styles: Record<string, string>) {
288
- const candidates = [
289
- { source: "Fill", value: styles["background-color"] },
290
- { source: "Text", value: styles.color },
291
- ];
292
-
293
- const deduped = new Map<string, { swatch: string; token: string; sources: string[] }>();
294
-
295
- for (const candidate of candidates) {
296
- if (!candidate.value) continue;
297
- const parsed = parseCssColor(candidate.value);
298
- if (!parsed || parsed.alpha <= 0) continue;
299
-
300
- const key = `${toColorPickerValue(candidate.value)}-${Math.round(parsed.alpha * 100)}`;
301
- const existing = deduped.get(key);
302
- if (existing) {
303
- existing.sources.push(candidate.source);
304
- continue;
305
- }
306
-
307
- deduped.set(key, {
308
- swatch: toColorPickerValue(candidate.value),
309
- token: formatColorToken(candidate.value),
310
- sources: [candidate.source],
311
- });
312
- }
313
-
314
- return Array.from(deduped.values());
315
- }
316
-
317
- function CommitField({
318
- value,
319
- disabled,
320
- liveCommit,
321
- onCommit,
322
- }: {
323
- value: string;
324
- disabled?: boolean;
325
- liveCommit?: boolean;
326
- onCommit: (nextValue: string) => void;
327
- }) {
328
- const [draft, setDraft] = useState(value);
329
- const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
330
- const valueRef = useRef(value);
331
-
332
- valueRef.current = value;
333
-
334
- useEffect(() => {
335
- setDraft(value);
336
- }, [value]);
337
-
338
- useEffect(
339
- () => () => {
340
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
341
- },
342
- [],
343
- );
344
-
345
- const commitDraft = (nextDraft: string) => {
346
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
347
- if (nextDraft !== valueRef.current) {
348
- onCommit(nextDraft);
349
- }
350
- };
351
-
352
- const scheduleCommit = (nextDraft: string) => {
353
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
354
- commitTimerRef.current = setTimeout(() => {
355
- if (nextDraft !== valueRef.current) {
356
- onCommit(nextDraft);
357
- }
358
- }, 120);
359
- };
360
-
361
- return (
362
- <input
363
- type="text"
364
- value={draft}
365
- disabled={disabled}
366
- onChange={(e) => {
367
- setDraft(e.target.value);
368
- if (liveCommit) scheduleCommit(e.target.value);
369
- }}
370
- onBlur={() => commitDraft(draft)}
371
- onWheel={(e) => {
372
- if (disabled) return;
373
- const delta = e.deltaY === 0 ? e.deltaX : e.deltaY;
374
- if (delta === 0) return;
375
- const nextDraft = adjustNumericToken(draft, delta < 0 ? 1 : -1, e);
376
- if (!nextDraft) return;
377
- e.preventDefault();
378
- setDraft(nextDraft);
379
- scheduleCommit(nextDraft);
380
- }}
381
- onKeyDown={(e) => {
382
- if (e.key === "Enter") {
383
- (e.target as HTMLInputElement).blur();
384
- return;
385
- }
386
- if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
387
- const nextDraft = adjustNumericToken(draft, e.key === "ArrowUp" ? 1 : -1, e);
388
- if (!nextDraft) return;
389
- e.preventDefault();
390
- setDraft(nextDraft);
391
- scheduleCommit(nextDraft);
392
- }}
393
- title={parseNumericToken(value) ? "Scroll or use Arrow keys to adjust" : undefined}
394
- className="min-w-0 w-full bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
395
- />
396
- );
397
- }
398
-
399
- function MetricField({
400
- label,
401
- value,
402
- disabled,
403
- liveCommit,
404
- onCommit,
405
- }: {
406
- label: string;
407
- value: string;
408
- disabled?: boolean;
409
- liveCommit?: boolean;
410
- onCommit: (nextValue: string) => void;
411
- }) {
412
- return (
413
- <div className={FIELD}>
414
- <div className="flex min-w-0 items-center gap-3">
415
- <span className="flex-shrink-0 text-[11px] font-medium text-neutral-500">{label}</span>
416
- <CommitField
417
- value={value}
418
- disabled={disabled}
419
- liveCommit={liveCommit}
420
- onCommit={onCommit}
421
- />
422
- </div>
423
- </div>
424
- );
425
- }
426
-
427
- function DetailField({
428
- label,
429
- value,
430
- disabled,
431
- onCommit,
432
- }: {
433
- label: string;
434
- value: string;
435
- disabled?: boolean;
436
- onCommit: (nextValue: string) => void;
437
- }) {
438
- return (
439
- <label className="grid min-w-0 gap-1.5">
440
- <span className={LABEL}>{label}</span>
441
- <div className={FIELD}>
442
- <CommitField value={value} disabled={disabled} onCommit={onCommit} />
443
- </div>
444
- </label>
445
- );
446
- }
447
-
448
- function TextAreaField({
449
- label,
450
- value,
451
- disabled,
452
- autoFocus,
453
- onCommit,
454
- }: {
455
- label: string;
456
- value: string;
457
- disabled?: boolean;
458
- autoFocus?: boolean;
459
- onCommit: (nextValue: string) => void;
460
- }) {
461
- const [draft, setDraft] = useState(value);
462
- const textareaRef = useRef<HTMLTextAreaElement | null>(null);
463
- const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
464
- const focusedRef = useRef(false);
465
- const valueRef = useRef(value);
466
-
467
- valueRef.current = value;
468
-
469
- useEffect(() => {
470
- if (focusedRef.current) return;
471
- setDraft(value);
472
- }, [value]);
473
-
474
- useEffect(
475
- () => () => {
476
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
477
- },
478
- [],
479
- );
480
-
481
- useEffect(() => {
482
- if (!autoFocus) return;
483
- textareaRef.current?.focus();
484
- }, [autoFocus]);
485
-
486
- const commitDraft = (nextDraft: string) => {
487
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
488
- if (nextDraft !== valueRef.current) {
489
- onCommit(nextDraft);
490
- }
491
- };
492
-
493
- const scheduleCommit = (nextDraft: string) => {
494
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
495
- commitTimerRef.current = setTimeout(() => {
496
- if (nextDraft !== valueRef.current) {
497
- onCommit(nextDraft);
498
- }
499
- }, 120);
500
- };
501
-
502
- return (
503
- <label className="grid min-w-0 gap-1.5">
504
- <span className={LABEL}>{label}</span>
505
- <div className={FIELD}>
506
- <textarea
507
- ref={textareaRef}
508
- value={draft}
509
- disabled={disabled}
510
- rows={4}
511
- onFocus={() => {
512
- focusedRef.current = true;
513
- }}
514
- onChange={(e) => {
515
- setDraft(e.target.value);
516
- scheduleCommit(e.target.value);
517
- }}
518
- onBlur={() => {
519
- focusedRef.current = false;
520
- commitDraft(draft);
521
- }}
522
- className="w-full resize-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
523
- />
524
- </div>
525
- </label>
526
- );
527
- }
528
-
529
- function formatTextFieldPreview(value: string): string {
530
- const collapsed = value.trim().replace(/\s+/g, " ");
531
- if (collapsed.length <= 56) return collapsed;
532
- return `${collapsed.slice(0, 55)}…`;
533
- }
534
-
535
- function getTextFieldColor(
536
- field: { computedStyles: Record<string, string> },
537
- inheritedStyles: Record<string, string>,
538
- ): string {
539
- return field.computedStyles.color || inheritedStyles.color || "rgb(0, 0, 0)";
540
- }
541
-
542
- function splitFontFamilies(value: string): string[] {
543
- const families: string[] = [];
544
- let current = "";
545
- let quote: '"' | "'" | null = null;
546
-
547
- for (const char of value) {
548
- if ((char === '"' || char === "'") && !quote) {
549
- quote = char;
550
- continue;
551
- }
552
- if (char === quote) {
553
- quote = null;
554
- continue;
555
- }
556
- if (char === "," && !quote) {
557
- if (current.trim()) families.push(current.trim());
558
- current = "";
559
- continue;
560
- }
561
- current += char;
562
- }
563
-
564
- if (current.trim()) families.push(current.trim());
565
- return families.map((family) => family.replace(/^["']|["']$/g, "").trim()).filter(Boolean);
566
- }
567
-
568
- function primaryFontFamily(value: string): string {
569
- return splitFontFamilies(value)[0] ?? "inherit";
570
- }
571
-
572
- function quoteFontFamily(family: string): string {
573
- const trimmed = family.trim();
574
- if (GENERIC_FONT_FAMILIES.has(trimmed.toLowerCase())) return trimmed;
575
- return `"${trimmed.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
576
- }
577
-
578
- function buildFontFamilyValue(family: string): string {
579
- const trimmed = family.trim();
580
- if (!trimmed) return "inherit";
581
- if (GENERIC_FONT_FAMILIES.has(trimmed.toLowerCase())) return trimmed;
582
- return `${quoteFontFamily(trimmed)}, ui-sans-serif, system-ui, sans-serif`;
583
- }
584
-
585
- function collectDocumentFontFamilies(): string[] {
586
- if (typeof document === "undefined") return [];
587
- const fontSet = document.fonts;
588
- if (!fontSet) return [];
589
- return Array.from(fontSet, (fontFace) => fontFace.family.replace(/^["']|["']$/g, "").trim())
590
- .filter(Boolean)
591
- .sort((a, b) => a.localeCompare(b));
592
- }
593
-
594
- function uniqueFontFamilies(values: string[]): string[] {
595
- const seen = new Set<string>();
596
- const result: string[] = [];
597
- for (const value of values) {
598
- const family = value.trim();
599
- if (!family) continue;
600
- const key = family.toLowerCase();
601
- if (seen.has(key)) continue;
602
- seen.add(key);
603
- result.push(family);
604
- }
605
- return result;
606
- }
607
-
608
- function uniqueFontOptions(values: FontOption[]): FontOption[] {
609
- const seen = new Set<string>();
610
- const result: FontOption[] = [];
611
- for (const value of values) {
612
- const family = value.family.trim();
613
- if (!family) continue;
614
- const key = family.toLowerCase();
615
- if (seen.has(key)) continue;
616
- seen.add(key);
617
- result.push({ family, source: value.source });
618
- }
619
- return result;
620
- }
621
-
622
- function fontSourceRank(source: FontSource): number {
623
- if (source === "Current") return 0;
624
- if (source === "Document") return 1;
625
- if (source === "Imported") return 2;
626
- if (source === "Local") return 3;
627
- if (source === "Google") return 4;
628
- return 5;
629
- }
630
-
631
- function sortFontOptions(options: FontOption[]): FontOption[] {
632
- return [...options].sort((a, b) => {
633
- const rankDelta = fontSourceRank(a.source) - fontSourceRank(b.source);
634
- if (rankDelta !== 0) return rankDelta;
635
-
636
- const commonA = COMMON_LOCAL_FONT_FAMILIES.findIndex(
637
- (family) => family.toLowerCase() === a.family.toLowerCase(),
638
- );
639
- const commonB = COMMON_LOCAL_FONT_FAMILIES.findIndex(
640
- (family) => family.toLowerCase() === b.family.toLowerCase(),
641
- );
642
- const commonDelta =
643
- (commonA === -1 ? Number.MAX_SAFE_INTEGER : commonA) -
644
- (commonB === -1 ? Number.MAX_SAFE_INTEGER : commonB);
645
-
646
- return commonDelta === 0 ? a.family.localeCompare(b.family) : commonDelta;
647
- });
648
- }
649
-
650
- function fontSearchKey(value: string): string {
651
- return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
652
- }
653
-
654
- function fontMatchesQuery(family: string, query: string): boolean {
655
- const normalizedQuery = query.trim().toLowerCase();
656
- if (!normalizedQuery) return true;
657
- const normalizedFamily = family.toLowerCase();
658
- if (normalizedFamily.includes(normalizedQuery)) return true;
659
- return fontSearchKey(family).includes(fontSearchKey(normalizedQuery));
660
- }
661
-
662
- function loadGoogleFontStylesheet(family: string): void {
663
- if (typeof document === "undefined") return;
664
- const trimmed = family.trim();
665
- if (!trimmed) return;
666
-
667
- const id = `studio-google-font-${trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
668
- if (document.getElementById(id)) return;
669
-
670
- const preconnect = document.querySelector('link[data-studio-google-font-preconnect="true"]');
671
- if (!preconnect) {
672
- const preconnectEl = document.createElement("link");
673
- preconnectEl.setAttribute("data-studio-google-font-preconnect", "true");
674
- preconnectEl.rel = "preconnect";
675
- preconnectEl.href = "https://fonts.gstatic.com";
676
- preconnectEl.crossOrigin = "anonymous";
677
- document.head.appendChild(preconnectEl);
678
- }
679
-
680
- const link = document.createElement("link");
681
- link.id = id;
682
- link.rel = "stylesheet";
683
- link.href = googleFontStylesheetUrl(trimmed);
684
- document.head.appendChild(link);
685
- }
686
-
687
- function loadImportedFontStylesheet(asset: ImportedFontAsset): void {
688
- if (typeof document === "undefined") return;
689
- const id = `studio-imported-font-${asset.family.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
690
- if (document.getElementById(id)) return;
691
-
692
- const style = document.createElement("style");
693
- style.id = id;
694
- style.textContent = importedFontFaceCss(asset);
695
- document.head.appendChild(style);
696
- }
697
-
698
- function FontWeightField({
699
- value,
700
- disabled,
701
- onCommit,
702
- }: {
703
- value: string;
704
- disabled?: boolean;
705
- onCommit: (nextValue: string) => void;
706
- }) {
707
- const options = ["300", "400", "500", "600", "700", "800"];
708
- return (
709
- <div className={FIELD}>
710
- <div className="flex min-w-0 items-center gap-3">
711
- <span className="flex-shrink-0 text-[11px] font-medium text-neutral-500">Weight</span>
712
- <select
713
- value={value}
714
- disabled={disabled}
715
- onChange={(e) => onCommit(e.target.value)}
716
- className="min-w-0 w-full appearance-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
717
- >
718
- {options.map((option) => (
719
- <option key={option} value={option}>
720
- {option}
721
- </option>
722
- ))}
723
- </select>
724
- </div>
725
- </div>
726
- );
727
- }
728
-
729
- function FontFamilyField({
730
- value,
731
- disabled,
732
- importedFonts,
733
- onImportFonts,
734
- onCommit,
735
- }: {
736
- value: string;
737
- disabled?: boolean;
738
- importedFonts: ImportedFontAsset[];
739
- onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;
740
- onCommit: (nextValue: string) => void;
741
- }) {
742
- const currentFamily = primaryFontFamily(value);
743
- const containerRef = useRef<HTMLDivElement | null>(null);
744
- const inputRef = useRef<HTMLInputElement | null>(null);
745
- const fontInputRef = useRef<HTMLInputElement | null>(null);
746
- const [open, setOpen] = useState(false);
747
- const [query, setQuery] = useState("");
748
- const [localFonts, setLocalFonts] = useState<string[]>([]);
749
- const [localFontData, setLocalFontData] = useState<LocalFontData[]>([]);
750
- const [googleFonts, setGoogleFonts] = useState<string[]>(() => [...POPULAR_GOOGLE_FONT_FAMILIES]);
751
- const [loadingLocalFonts, setLoadingLocalFonts] = useState(false);
752
- const [loadingGoogleFonts, setLoadingGoogleFonts] = useState(false);
753
- const [importingFonts, setImportingFonts] = useState(false);
754
- const [fontNotice, setFontNotice] = useState<string | null>(null);
755
- const canQueryLocalFonts =
756
- typeof window !== "undefined" && typeof window.queryLocalFonts === "function";
757
-
758
- useEffect(() => {
759
- if (!open) return;
760
- const handlePointerDown = (event: PointerEvent) => {
761
- const target = event.target;
762
- if (!(target instanceof Node)) return;
763
- if (!containerRef.current?.contains(target)) setOpen(false);
764
- };
765
- document.addEventListener("pointerdown", handlePointerDown);
766
- return () => {
767
- document.removeEventListener("pointerdown", handlePointerDown);
768
- };
769
- }, [open]);
770
-
771
- useEffect(() => {
772
- if (!open) return;
773
- requestAnimationFrame(() => inputRef.current?.focus());
774
- }, [open]);
775
-
776
- useEffect(() => {
777
- let cancelled = false;
778
- void fetch("/api/fonts")
779
- .then((response) => (response.ok ? response.json() : null))
780
- .then((data: { fonts?: string[] } | null) => {
781
- const fonts = data?.fonts;
782
- if (cancelled || !Array.isArray(fonts)) return;
783
- setLocalFonts((current) => uniqueFontFamilies([...current, ...fonts]));
784
- })
785
- .catch(() => undefined);
786
- return () => {
787
- cancelled = true;
788
- };
789
- }, []);
790
-
791
- useEffect(() => {
792
- let cancelled = false;
793
- setLoadingGoogleFonts(true);
794
- void fetch("/api/fonts/google")
795
- .then((response) => (response.ok ? response.json() : null))
796
- .then((data: { fonts?: string[] } | null) => {
797
- const fonts = data?.fonts;
798
- if (cancelled || !Array.isArray(fonts)) return;
799
- setGoogleFonts(uniqueFontFamilies([...fonts, ...POPULAR_GOOGLE_FONT_FAMILIES]));
800
- })
801
- .catch(() => undefined)
802
- .finally(() => {
803
- if (!cancelled) setLoadingGoogleFonts(false);
804
- });
805
- return () => {
806
- cancelled = true;
807
- };
808
- }, []);
809
-
810
- useEffect(() => {
811
- if (googleFonts.some((family) => family.toLowerCase() === currentFamily.toLowerCase())) {
812
- loadGoogleFontStylesheet(currentFamily);
813
- }
814
- const imported = importedFonts.find(
815
- (font) => font.family.toLowerCase() === currentFamily.toLowerCase(),
816
- );
817
- if (imported) loadImportedFontStylesheet(imported);
818
- }, [currentFamily, googleFonts, importedFonts]);
819
-
820
- const loadBrowserLocalFonts = async () => {
821
- if (!canQueryLocalFonts || !window.queryLocalFonts) {
822
- setFontNotice("This browser does not expose installed fonts. Import a font file instead.");
823
- return;
824
- }
825
- setLoadingLocalFonts(true);
826
- setFontNotice(null);
827
- try {
828
- const fonts = await window.queryLocalFonts();
829
- const sortedFonts = [...fonts].sort((a, b) => localFontSortScore(a) - localFontSortScore(b));
830
- const families = sortedFonts
831
- .map((font) => font.family)
832
- .filter((name): name is string => Boolean(name))
833
- .map((name) => fontFamilyFromAssetPath(`${name}.ttf`));
834
- setLocalFontData(sortedFonts);
835
- setLocalFonts((current) => uniqueFontFamilies([...current, ...families]));
836
- setFontNotice(fonts.length === 0 ? "No browser-local fonts were returned." : null);
837
- } catch (error) {
838
- const name = error instanceof Error ? error.name : "";
839
- setFontNotice(
840
- name === "NotAllowedError"
841
- ? "Local font access was denied. Import a font file instead."
842
- : "Local font access is unavailable. Import a font file instead.",
843
- );
844
- } finally {
845
- setLoadingLocalFonts(false);
846
- }
847
- };
848
-
849
- const handleImportFonts = async (files: FileList | File[] | null) => {
850
- if (!files?.length || !onImportFonts) return;
851
- setImportingFonts(true);
852
- setFontNotice(null);
853
- try {
854
- const imported = await onImportFonts(files);
855
- for (const font of imported) loadImportedFontStylesheet(font);
856
- const first = imported[0];
857
- if (first) {
858
- onCommit(buildFontFamilyValue(first.family));
859
- setQuery("");
860
- setOpen(false);
861
- } else {
862
- setFontNotice("No supported font files were imported.");
863
- }
864
- } finally {
865
- setImportingFonts(false);
866
- }
867
- };
868
-
869
- const projectFontAssets = useMemo(
870
- () =>
871
- uniqueFontOptions(
872
- importedFonts.map((font): FontOption => ({ family: font.family, source: "Imported" })),
873
- ),
874
- [importedFonts],
875
- );
876
-
877
- const options = useMemo(() => {
878
- const documentFonts = collectDocumentFontFamilies();
879
- return sortFontOptions(
880
- uniqueFontOptions([
881
- { family: currentFamily, source: "Current" },
882
- ...documentFonts.map((family): FontOption => ({ family, source: "Document" })),
883
- ...projectFontAssets,
884
- ...localFonts.map((family): FontOption => ({ family, source: "Local" })),
885
- ...googleFonts.map((family): FontOption => ({ family, source: "Google" })),
886
- ...DEFAULT_FONT_FAMILIES.map((family): FontOption => ({ family, source: "System" })),
887
- ]),
888
- );
889
- }, [currentFamily, googleFonts, localFonts, projectFontAssets]);
890
-
891
- const filteredOptions = useMemo(() => {
892
- const matches = options.filter((option) => fontMatchesQuery(option.family, query));
893
- return matches.slice(0, query.trim() ? 120 : 160);
894
- }, [options, query]);
895
-
896
- const importLocalFont = async (family: string): Promise<ImportedFontAsset | null> => {
897
- if (!onImportFonts) return null;
898
- const candidates = localFontData
899
- .filter((font) => fontFamilyFromAssetPath(`${font.family}.ttf`) === family)
900
- .sort((a, b) => localFontSortScore(a) - localFontSortScore(b));
901
- const font = candidates.find((entry) => typeof entry.blob === "function");
902
- if (!font?.blob) return null;
903
-
904
- const blob = await font.blob();
905
- const style = sanitizeFontFilePart(font.style ?? "Regular") || "Regular";
906
- const name = sanitizeFontFilePart(`${family} ${style}`) || family;
907
- const file = new File([blob], `${name}.ttf`, {
908
- type: blob.type || "font/ttf",
909
- });
910
- const imported = await onImportFonts([file]);
911
- return (
912
- imported.find((asset) => asset.family.toLowerCase() === family.toLowerCase()) ??
913
- imported[0] ??
914
- null
915
- );
916
- };
917
-
918
- const commitFamily = async (option: FontOption) => {
919
- if (option.source === "Local") {
920
- setImportingFonts(true);
921
- setFontNotice(null);
922
- try {
923
- const imported = await importLocalFont(option.family);
924
- if (imported) {
925
- loadImportedFontStylesheet(imported);
926
- onCommit(buildFontFamilyValue(imported.family));
927
- setQuery("");
928
- setOpen(false);
929
- return;
930
- }
931
- onCommit(buildFontFamilyValue(option.family));
932
- setQuery("");
933
- setOpen(false);
934
- } finally {
935
- setImportingFonts(false);
936
- }
937
- return;
938
- }
939
-
940
- if (option.source === "Google") {
941
- loadGoogleFontStylesheet(option.family);
942
- }
943
- const imported = importedFonts.find(
944
- (font) => font.family.toLowerCase() === option.family.toLowerCase(),
945
- );
946
- if (imported) loadImportedFontStylesheet(imported);
947
- onCommit(buildFontFamilyValue(option.family));
948
- setQuery("");
949
- setOpen(false);
950
- };
951
-
952
- return (
953
- <div ref={containerRef} className="relative grid min-w-0 gap-1.5">
954
- <span className={LABEL}>Font family</span>
955
- <button
956
- type="button"
957
- disabled={disabled}
958
- onClick={() => setOpen((next) => !next)}
959
- className={`${FIELD} flex h-10 items-center justify-between gap-3 text-left hover:border-neutral-700 disabled:cursor-not-allowed`}
960
- >
961
- <span
962
- className="min-w-0 flex-1 truncate text-[11px] font-medium text-neutral-100"
963
- style={{ fontFamily: value }}
964
- >
965
- {currentFamily}
966
- </span>
967
- <span className="flex-shrink-0 text-[10px] uppercase tracking-[0.14em] text-neutral-600">
968
- Font
969
- </span>
970
- </button>
971
-
972
- {open && (
973
- <div className="absolute left-0 right-0 top-[calc(100%+6px)] z-50 overflow-hidden rounded-xl border border-neutral-700 bg-neutral-950 shadow-2xl">
974
- <div className="grid grid-cols-[minmax(0,1fr)_auto_auto] gap-2 border-b border-neutral-800 p-2">
975
- <input
976
- ref={inputRef}
977
- type="text"
978
- value={query}
979
- disabled={disabled}
980
- placeholder={loadingGoogleFonts ? "Loading Google Fonts..." : "Search fonts"}
981
- onChange={(e) => setQuery(e.target.value)}
982
- onKeyDown={(e) => {
983
- if (e.key === "Escape") {
984
- e.preventDefault();
985
- setOpen(false);
986
- }
987
- if (e.key === "Enter" && filteredOptions[0]) {
988
- e.preventDefault();
989
- commitFamily(filteredOptions[0]);
990
- }
991
- }}
992
- className="min-w-0 rounded-lg border border-neutral-800 bg-neutral-900 px-2.5 py-2 text-[11px] font-medium text-neutral-100 outline-none placeholder:text-neutral-600 focus:border-neutral-600"
993
- />
994
- {canQueryLocalFonts && (
995
- <button
996
- type="button"
997
- disabled={disabled || loadingLocalFonts}
998
- onClick={loadBrowserLocalFonts}
999
- className="rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 text-[10px] font-medium text-neutral-400 transition-colors hover:border-neutral-600 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-700"
1000
- >
1001
- {loadingLocalFonts ? "..." : "Local"}
1002
- </button>
1003
- )}
1004
- <button
1005
- type="button"
1006
- disabled={disabled || importingFonts || !onImportFonts}
1007
- onClick={() => fontInputRef.current?.click()}
1008
- className="rounded-lg border border-neutral-700 bg-neutral-900 px-2.5 text-[10px] font-medium text-neutral-400 transition-colors hover:border-neutral-600 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-700"
1009
- >
1010
- {importingFonts ? "..." : "Import"}
1011
- </button>
1012
- <input
1013
- ref={fontInputRef}
1014
- type="file"
1015
- accept=".ttf,.otf,.ttc,.woff,.woff2,.eot,font/*"
1016
- multiple
1017
- aria-label="Import local font files"
1018
- disabled={disabled || importingFonts || !onImportFonts}
1019
- className="hidden"
1020
- onChange={async (event) => {
1021
- await handleImportFonts(event.target.files);
1022
- event.target.value = "";
1023
- }}
1024
- />
1025
- </div>
1026
- {fontNotice && (
1027
- <div className="border-b border-neutral-800 px-3 py-2 text-[10px] leading-4 text-neutral-500">
1028
- {fontNotice}
1029
- </div>
1030
- )}
1031
- <div className="max-h-64 overflow-y-auto p-1">
1032
- {filteredOptions.length === 0 ? (
1033
- <div className="px-2 py-3 text-[11px] text-neutral-500">No fonts found.</div>
1034
- ) : (
1035
- filteredOptions.map((option) => (
1036
- <button
1037
- key={`${option.source}-${option.family}`}
1038
- type="button"
1039
- onClick={() => commitFamily(option)}
1040
- className={`flex w-full min-w-0 items-center justify-between gap-3 rounded-lg px-2 py-2 text-left text-[11px] transition-colors ${
1041
- option.family === currentFamily
1042
- ? "bg-studio-accent/15 text-neutral-50"
1043
- : "text-neutral-300 hover:bg-neutral-900 hover:text-neutral-100"
1044
- }`}
1045
- >
1046
- <span className="min-w-0 truncate font-medium">{option.family}</span>
1047
- <span className="flex-shrink-0 text-[9px] uppercase tracking-[0.14em] text-neutral-600">
1048
- {option.source}
1049
- </span>
1050
- </button>
1051
- ))
1052
- )}
1053
- </div>
1054
- </div>
1055
- )}
1056
- </div>
1057
- );
1058
- }
1059
-
1060
- function ColorField({
17
+ function PropertyRow({
1061
18
  label,
1062
19
  value,
1063
- disabled,
1064
- onCommit,
20
+ onChange,
1065
21
  }: {
1066
22
  label: string;
1067
23
  value: string;
1068
- disabled?: boolean;
1069
- onCommit: (nextValue: string) => void;
1070
- }) {
1071
- const buttonRef = useRef<HTMLButtonElement | null>(null);
1072
- const panelRef = useRef<HTMLDivElement | null>(null);
1073
- const [open, setOpen] = useState(false);
1074
- const [panelPosition, setPanelPosition] = useState<FloatingPosition | null>(null);
1075
- const [draftColor, setDraftColor] = useState<ParsedColor>(() => colorFromCss(value));
1076
- const [hexDraft, setHexDraft] = useState(() => toHexColor(colorFromCss(value)).toUpperCase());
1077
- const hsv = rgbToHsv(draftColor);
1078
- const hueColor = formatCssColor({
1079
- ...hsvToRgb({ hue: hsv.hue, saturation: 1, value: 1 }),
1080
- alpha: 1,
1081
- });
1082
- const opaqueColor = formatCssColor({ ...draftColor, alpha: 1 });
1083
- const currentColor = formatCssColor(draftColor);
1084
- const saturationPercent = Math.round(hsv.saturation * 100);
1085
- const brightnessPercent = Math.round(hsv.value * 100);
1086
- const alphaPercent = Math.round(draftColor.alpha * 100);
1087
-
1088
- useEffect(() => {
1089
- const nextColor = colorFromCss(value);
1090
- setDraftColor(nextColor);
1091
- setHexDraft(toHexColor(nextColor).toUpperCase());
1092
- }, [value]);
1093
-
1094
- const updatePanelPosition = useCallback(() => {
1095
- const anchor = buttonRef.current?.getBoundingClientRect();
1096
- if (!anchor) return;
1097
- const measured = panelRef.current?.getBoundingClientRect();
1098
- setPanelPosition(
1099
- resolveFloatingPanelPosition(
1100
- anchor,
1101
- { width: window.innerWidth, height: window.innerHeight },
1102
- {
1103
- width: measured?.width || COLOR_PICKER_SIZE.width,
1104
- height: measured?.height || COLOR_PICKER_SIZE.height,
1105
- },
1106
- ),
1107
- );
1108
- }, []);
1109
-
1110
- useLayoutEffect(() => {
1111
- if (!open) return;
1112
- updatePanelPosition();
1113
-
1114
- const handlePositionInvalidated = () => updatePanelPosition();
1115
- window.addEventListener("resize", handlePositionInvalidated);
1116
- window.addEventListener("scroll", handlePositionInvalidated, true);
1117
- return () => {
1118
- window.removeEventListener("resize", handlePositionInvalidated);
1119
- window.removeEventListener("scroll", handlePositionInvalidated, true);
1120
- };
1121
- }, [open, updatePanelPosition]);
1122
-
1123
- useEffect(() => {
1124
- if (!open) return;
1125
-
1126
- const handlePointerDown = (event: PointerEvent) => {
1127
- const target = event.target as Node | null;
1128
- if (!target) return;
1129
- if (panelRef.current?.contains(target) || buttonRef.current?.contains(target)) return;
1130
- setOpen(false);
1131
- };
1132
- const handleKeyDown = (event: KeyboardEvent) => {
1133
- if (event.key === "Escape") setOpen(false);
1134
- };
1135
-
1136
- document.addEventListener("pointerdown", handlePointerDown);
1137
- document.addEventListener("keydown", handleKeyDown);
1138
- return () => {
1139
- document.removeEventListener("pointerdown", handlePointerDown);
1140
- document.removeEventListener("keydown", handleKeyDown);
1141
- };
1142
- }, [open]);
1143
-
1144
- const commitColor = (nextColor: ParsedColor) => {
1145
- setDraftColor(nextColor);
1146
- setHexDraft(toHexColor(nextColor).toUpperCase());
1147
- onCommit(formatCssColor(nextColor));
1148
- };
1149
-
1150
- const commitHsv = (nextHsv: { hue?: number; saturation?: number; value?: number }) => {
1151
- const rgb = hsvToRgb({
1152
- hue: nextHsv.hue ?? hsv.hue,
1153
- saturation: nextHsv.saturation ?? hsv.saturation,
1154
- value: nextHsv.value ?? hsv.value,
1155
- });
1156
- commitColor({ ...rgb, alpha: draftColor.alpha });
1157
- };
1158
-
1159
- const updateSaturationValue = (clientX: number, clientY: number, target: HTMLDivElement) => {
1160
- const rect = target.getBoundingClientRect();
1161
- const saturation = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
1162
- const nextValue = Math.max(0, Math.min(1, 1 - (clientY - rect.top) / rect.height));
1163
- commitHsv({ saturation, value: nextValue });
1164
- };
1165
-
1166
- const handleHexCommit = (nextHex: string) => {
1167
- setHexDraft(nextHex);
1168
- const normalized = nextHex.trim().startsWith("#") ? nextHex.trim() : `#${nextHex.trim()}`;
1169
- const parsed = parseCssColor(normalized);
1170
- if (!parsed) return;
1171
- commitColor({ ...parsed, alpha: draftColor.alpha });
1172
- };
1173
-
1174
- const picker = open
1175
- ? createPortal(
1176
- <div
1177
- ref={panelRef}
1178
- className="fixed z-[9999] w-[292px] overflow-hidden rounded-2xl border border-neutral-700 bg-neutral-950 shadow-2xl shadow-black/50"
1179
- style={{
1180
- left: panelPosition?.left ?? -9999,
1181
- top: panelPosition?.top ?? -9999,
1182
- }}
1183
- >
1184
- <div className="flex items-center justify-between border-b border-neutral-800 px-3 py-2">
1185
- <div className="min-w-0">
1186
- <div className="truncate text-[11px] font-medium text-neutral-100">{label}</div>
1187
- <div className="text-[9px] uppercase tracking-[0.16em] text-neutral-600">Color</div>
1188
- </div>
1189
- <button
1190
- type="button"
1191
- onClick={() => setOpen(false)}
1192
- className="flex h-7 w-7 items-center justify-center rounded-lg text-neutral-500 transition-colors hover:bg-neutral-900 hover:text-neutral-200"
1193
- aria-label="Close color picker"
1194
- >
1195
- <X size={13} />
1196
- </button>
1197
- </div>
1198
- <div className="space-y-3 p-3">
1199
- <div
1200
- className="relative h-36 cursor-crosshair overflow-hidden rounded-xl border border-neutral-700 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.06)]"
1201
- style={{
1202
- backgroundColor: hueColor,
1203
- }}
1204
- onPointerDown={(event) => {
1205
- event.currentTarget.setPointerCapture(event.pointerId);
1206
- updateSaturationValue(event.clientX, event.clientY, event.currentTarget);
1207
- }}
1208
- onPointerMove={(event) => {
1209
- if (event.buttons !== 1) return;
1210
- updateSaturationValue(event.clientX, event.clientY, event.currentTarget);
1211
- }}
1212
- >
1213
- <div className="absolute inset-0 bg-gradient-to-r from-white to-transparent" />
1214
- <div className="absolute inset-0 bg-gradient-to-t from-black to-transparent" />
1215
- <div
1216
- className="pointer-events-none absolute top-0 h-full w-px -translate-x-1/2 bg-white/70 shadow-[0_0_0_1px_rgba(0,0,0,0.45)] mix-blend-difference"
1217
- style={{ left: `${hsv.saturation * 100}%` }}
1218
- />
1219
- <div
1220
- className="pointer-events-none absolute left-0 h-px w-full -translate-y-1/2 bg-white/70 shadow-[0_0_0_1px_rgba(0,0,0,0.45)] mix-blend-difference"
1221
- style={{ top: `${(1 - hsv.value) * 100}%` }}
1222
- />
1223
- <div
1224
- className="pointer-events-none absolute h-6 w-6 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.85),0_8px_18px_rgba(0,0,0,0.45)]"
1225
- style={{
1226
- left: `${hsv.saturation * 100}%`,
1227
- top: `${(1 - hsv.value) * 100}%`,
1228
- backgroundColor: opaqueColor,
1229
- }}
1230
- />
1231
- </div>
1232
-
1233
- <div className="flex min-w-0 items-center gap-3">
1234
- <div
1235
- className="h-9 w-9 flex-shrink-0 rounded-xl border border-neutral-600 shadow-[inset_0_1px_0_rgba(255,255,255,0.08)]"
1236
- style={{ backgroundColor: currentColor }}
1237
- />
1238
- <div className="min-w-0 flex-1">
1239
- <div className="truncate text-[11px] font-medium text-neutral-100">
1240
- {currentColor}
1241
- </div>
1242
- <div className="mt-0.5 text-[9px] uppercase tracking-[0.12em] text-neutral-600">
1243
- S {saturationPercent}% · B {brightnessPercent}% · A {alphaPercent}%
1244
- </div>
1245
- </div>
1246
- </div>
1247
-
1248
- <ColorSlider
1249
- label="Hue"
1250
- value={hsv.hue}
1251
- min={0}
1252
- max={360}
1253
- step={1}
1254
- displayValue={`${Math.round(hsv.hue)}°`}
1255
- background="linear-gradient(90deg, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)"
1256
- thumbColor={hueColor}
1257
- disabled={disabled}
1258
- onCommit={(nextHue) => commitHsv({ hue: nextHue })}
1259
- />
1260
-
1261
- <ColorSlider
1262
- label="Alpha"
1263
- value={draftColor.alpha}
1264
- min={0}
1265
- max={1}
1266
- step={0.01}
1267
- displayValue={`${alphaPercent}%`}
1268
- background={`linear-gradient(90deg, transparent, ${opaqueColor})`}
1269
- thumbColor={currentColor}
1270
- disabled={disabled}
1271
- onCommit={(nextAlpha) => commitColor({ ...draftColor, alpha: nextAlpha })}
1272
- />
1273
-
1274
- <label className="grid gap-1.5">
1275
- <span className={LABEL}>Hex</span>
1276
- <input
1277
- value={hexDraft}
1278
- onChange={(event) => handleHexCommit(event.target.value)}
1279
- className={`${FIELD} h-10 w-full text-[11px] font-medium outline-none`}
1280
- spellCheck={false}
1281
- />
1282
- </label>
1283
- </div>
1284
- </div>,
1285
- document.body,
1286
- )
1287
- : null;
1288
-
1289
- const openPicker = () => {
1290
- if (disabled) return;
1291
- setOpen((current) => !current);
1292
- if (!open) {
1293
- requestAnimationFrame(updatePanelPosition);
1294
- }
1295
- };
1296
-
1297
- return (
1298
- <div className="grid min-w-0 gap-1.5">
1299
- <span className={LABEL}>{label}</span>
1300
- <button
1301
- type="button"
1302
- disabled={disabled}
1303
- aria-label={`Pick ${label.toLowerCase()} color`}
1304
- ref={buttonRef}
1305
- onClick={openPicker}
1306
- className={`${FIELD} flex items-center gap-3 text-left hover:border-neutral-700 disabled:cursor-not-allowed ${open ? "border-neutral-600" : ""}`}
1307
- >
1308
- <div
1309
- className="relative h-7 w-7 flex-shrink-0 overflow-hidden rounded-lg border border-neutral-700 bg-neutral-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]"
1310
- style={{ backgroundColor: value || "transparent" }}
1311
- />
1312
- <span className="min-w-0 flex-1 truncate text-[11px] font-medium text-neutral-100">
1313
- {value}
1314
- </span>
1315
- </button>
1316
- {picker}
1317
- </div>
1318
- );
1319
- }
1320
-
1321
- function ColorSlider({
1322
- label,
1323
- value,
1324
- min,
1325
- max,
1326
- step,
1327
- displayValue,
1328
- background,
1329
- thumbColor,
1330
- disabled,
1331
- onCommit,
1332
- }: {
1333
- label: string;
1334
- value: number;
1335
- min: number;
1336
- max: number;
1337
- step: number;
1338
- displayValue: string;
1339
- background: string;
1340
- thumbColor: string;
1341
- disabled?: boolean;
1342
- onCommit: (nextValue: number) => void;
1343
- }) {
1344
- const trackRef = useRef<HTMLDivElement | null>(null);
1345
- const percent = ((value - min) / (max - min)) * 100;
1346
-
1347
- const commitFromClientX = (clientX: number) => {
1348
- const rect = trackRef.current?.getBoundingClientRect();
1349
- if (!rect || rect.width <= 0) return;
1350
- const rawValue = min + ((clientX - rect.left) / rect.width) * (max - min);
1351
- const stepped = Math.round(rawValue / step) * step;
1352
- onCommit(Math.max(min, Math.min(max, stepped)));
1353
- };
1354
-
1355
- const commitKeyboardValue = (nextValue: number) => {
1356
- onCommit(Math.max(min, Math.min(max, nextValue)));
1357
- };
1358
-
1359
- return (
1360
- <div className="grid gap-1.5">
1361
- <div className="flex items-center justify-between">
1362
- <span className={LABEL}>{label}</span>
1363
- <span className="text-[10px] font-medium text-neutral-400">{displayValue}</span>
1364
- </div>
1365
- <div
1366
- ref={trackRef}
1367
- role="slider"
1368
- tabIndex={disabled ? -1 : 0}
1369
- aria-label={label}
1370
- aria-valuemin={min}
1371
- aria-valuemax={max}
1372
- aria-valuenow={value}
1373
- aria-disabled={disabled}
1374
- className={`relative h-4 rounded-full border border-neutral-700 shadow-[inset_0_1px_2px_rgba(0,0,0,0.55)] outline-none focus:border-[#f5a400] focus:ring-2 focus:ring-[#f5a400]/40 ${
1375
- disabled ? "cursor-not-allowed opacity-50" : "cursor-ew-resize"
1376
- }`}
1377
- style={{ background }}
1378
- onPointerDown={(event) => {
1379
- if (disabled) return;
1380
- event.currentTarget.setPointerCapture(event.pointerId);
1381
- commitFromClientX(event.clientX);
1382
- }}
1383
- onPointerMove={(event) => {
1384
- if (disabled || event.buttons !== 1) return;
1385
- commitFromClientX(event.clientX);
1386
- }}
1387
- onKeyDown={(event) => {
1388
- if (disabled) return;
1389
- if (event.key === "ArrowRight" || event.key === "ArrowUp") {
1390
- event.preventDefault();
1391
- commitKeyboardValue(value + step);
1392
- } else if (event.key === "ArrowLeft" || event.key === "ArrowDown") {
1393
- event.preventDefault();
1394
- commitKeyboardValue(value - step);
1395
- } else if (event.key === "Home") {
1396
- event.preventDefault();
1397
- commitKeyboardValue(min);
1398
- } else if (event.key === "End") {
1399
- event.preventDefault();
1400
- commitKeyboardValue(max);
1401
- }
1402
- }}
1403
- >
1404
- <div
1405
- className="pointer-events-none absolute top-1/2 h-6 w-6 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.85),0_6px_14px_rgba(0,0,0,0.5)]"
1406
- style={{ left: `${Math.max(0, Math.min(100, percent))}%`, backgroundColor: thumbColor }}
1407
- />
1408
- </div>
1409
- </div>
1410
- );
1411
- }
1412
-
1413
- function ImageFillField({
1414
- projectId,
1415
- sourceFile,
1416
- value,
1417
- assets,
1418
- disabled,
1419
- onCommit,
1420
- onImportAssets,
1421
- }: {
1422
- projectId: string;
1423
- sourceFile: string;
1424
- value: string;
1425
- assets: string[];
1426
- disabled?: boolean;
1427
- onCommit: (nextValue: string) => void;
1428
- onImportAssets?: (files: FileList) => Promise<string[]>;
1429
- }) {
1430
- const fileInputRef = useRef<HTMLInputElement | null>(null);
1431
- const [uploading, setUploading] = useState(false);
1432
- const imageAssets = useMemo(() => assets.filter((asset) => IMAGE_EXT.test(asset)), [assets]);
1433
- const selectedAsset = useMemo(
1434
- () => resolveSelectedAsset(value, sourceFile, imageAssets),
1435
- [imageAssets, sourceFile, value],
1436
- );
1437
- const externalUrlValue = selectedAsset ? "" : value;
1438
-
1439
- const handleUpload = async (files: FileList | null) => {
1440
- if (!files?.length || !onImportAssets) return;
1441
- setUploading(true);
1442
- try {
1443
- const uploaded = await onImportAssets(files);
1444
- const nextImage = uploaded.find((asset) => IMAGE_EXT.test(asset));
1445
- if (nextImage) {
1446
- onCommit(`url("${toProjectRootAssetPath(nextImage)}")`);
1447
- }
1448
- } finally {
1449
- setUploading(false);
1450
- }
1451
- };
1452
-
1453
- return (
1454
- <div className="space-y-4">
1455
- <div className="grid min-w-0 gap-1.5">
1456
- <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
1457
- <span className={LABEL}>Project asset</span>
1458
- <button
1459
- type="button"
1460
- disabled={disabled || uploading}
1461
- onClick={() => fileInputRef.current?.click()}
1462
- className={`inline-flex h-7 max-w-full items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors ${
1463
- disabled || uploading
1464
- ? "cursor-not-allowed text-neutral-600"
1465
- : "cursor-pointer hover:border-neutral-600 hover:text-white"
1466
- }`}
1467
- >
1468
- <Plus size={12} className="flex-shrink-0" />
1469
- <span className="truncate">{uploading ? "Uploading…" : "Upload image"}</span>
1470
- </button>
1471
- <input
1472
- ref={fileInputRef}
1473
- type="file"
1474
- accept="image/*"
1475
- aria-label="Upload image asset"
1476
- disabled={disabled || uploading}
1477
- className="hidden"
1478
- onChange={async (event) => {
1479
- await handleUpload(event.target.files);
1480
- event.target.value = "";
1481
- }}
1482
- />
1483
- </div>
1484
- {imageAssets.length > 0 ? (
1485
- <div className="space-y-3">
1486
- {selectedAsset && (
1487
- <div className="overflow-hidden rounded-xl border border-neutral-800 bg-neutral-900/80">
1488
- <img
1489
- src={`/api/projects/${projectId}/preview/${selectedAsset}`}
1490
- alt={selectedAsset.split("/").pop() ?? selectedAsset}
1491
- className="h-28 w-full object-contain bg-neutral-950/80"
1492
- />
1493
- </div>
1494
- )}
1495
- <div className={FIELD}>
1496
- <select
1497
- value={selectedAsset ?? ""}
1498
- disabled={disabled}
1499
- onChange={(e) => {
1500
- const nextAsset = e.target.value;
1501
- if (!nextAsset) {
1502
- onCommit("none");
1503
- return;
1504
- }
1505
- onCommit(`url("${toProjectRootAssetPath(nextAsset)}")`);
1506
- }}
1507
- className="min-w-0 w-full appearance-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
1508
- >
1509
- <option value="">None</option>
1510
- {imageAssets.map((asset) => (
1511
- <option key={asset} value={asset}>
1512
- {asset}
1513
- </option>
1514
- ))}
1515
- </select>
1516
- </div>
1517
- </div>
1518
- ) : (
1519
- <div className="rounded-xl border border-dashed border-neutral-800 bg-neutral-900/50 px-3 py-3 text-[11px] leading-5 text-neutral-500">
1520
- No image assets yet. Upload one here and Studio will also add it to the Assets tab.
1521
- </div>
1522
- )}
1523
- </div>
1524
-
1525
- <DetailField
1526
- label="External URL"
1527
- value={externalUrlValue}
1528
- disabled={disabled}
1529
- onCommit={(next) => onCommit(next.trim() ? `url("${next.trim()}")` : "none")}
1530
- />
1531
- </div>
1532
- );
1533
- }
1534
-
1535
- function GradientField({
1536
- value,
1537
- fallbackColor,
1538
- disabled,
1539
- onCommit,
1540
- }: {
1541
- value: string;
1542
- fallbackColor: string | undefined;
1543
- disabled?: boolean;
1544
- onCommit: (nextValue: string) => void;
1545
- }) {
1546
- const previewRef = useRef<HTMLDivElement | null>(null);
1547
- const parsed = parseGradient(value) ?? buildDefaultGradientModel(fallbackColor);
1548
-
1549
- const commit = (next: GradientModel) => onCommit(serializeGradient(next));
1550
-
1551
- const patch = (partial: Partial<GradientModel>) => commit({ ...parsed, ...partial });
1552
-
1553
- const updateStop = (index: number, partial: Partial<GradientModel["stops"][number]>) => {
1554
- const stops = parsed.stops.map((stop, stopIndex) =>
1555
- stopIndex === index ? { ...stop, ...partial } : stop,
1556
- );
1557
- commit({ ...parsed, stops });
1558
- };
1559
-
1560
- const addStop = (position?: number) => {
1561
- const nextGradient =
1562
- position != null
1563
- ? insertGradientStop(parsed, position)
1564
- : insertGradientStop(
1565
- parsed,
1566
- parsed.stops.at(-1)?.position != null
1567
- ? Math.min(100, (parsed.stops.at(-1)?.position ?? 90) + 10)
1568
- : 100,
1569
- );
1570
- commit(nextGradient);
1571
- };
1572
-
1573
- const removeStop = (index: number) => {
1574
- if (parsed.stops.length <= 2) return;
1575
- commit({ ...parsed, stops: parsed.stops.filter((_, stopIndex) => stopIndex !== index) });
1576
- };
1577
-
1578
- const previewStyle = {
1579
- backgroundImage: serializeGradient(parsed),
1580
- };
1581
-
1582
- return (
1583
- <div className="space-y-4">
1584
- <div className={`${FIELD} space-y-3 p-3`}>
1585
- <div
1586
- ref={previewRef}
1587
- className="relative h-11 overflow-hidden rounded-lg border border-neutral-700"
1588
- style={previewStyle}
1589
- onClick={(event) => {
1590
- if (disabled) return;
1591
- const rect = previewRef.current?.getBoundingClientRect();
1592
- if (!rect || rect.width <= 0) return;
1593
- const position = ((event.clientX - rect.left) / rect.width) * 100;
1594
- addStop(position);
1595
- }}
1596
- >
1597
- {parsed.stops.map((stop, index) => (
1598
- <div
1599
- key={`stop-preview-${index}`}
1600
- className="absolute top-1/2 h-4 w-4 -translate-y-1/2 rounded-full border-2 border-white/90 shadow-[0_0_0_1px_rgba(0,0,0,0.35)]"
1601
- style={{
1602
- left: `calc(${stop.position}% - 8px)`,
1603
- backgroundColor: stop.color,
1604
- }}
1605
- />
1606
- ))}
1607
- </div>
1608
- <div className="flex min-w-0 flex-wrap items-center gap-2">
1609
- <SegmentedControl
1610
- disabled={disabled}
1611
- value={parsed.kind}
1612
- onChange={(next) => patch({ kind: next as GradientModel["kind"] })}
1613
- options={[
1614
- { label: "Linear", value: "linear" },
1615
- { label: "Radial", value: "radial" },
1616
- { label: "Conic", value: "conic" },
1617
- ]}
1618
- />
1619
- <label className="flex items-center gap-2 text-[11px] font-medium text-neutral-400">
1620
- <input
1621
- type="checkbox"
1622
- checked={parsed.repeating}
1623
- disabled={disabled}
1624
- onChange={(e) => patch({ repeating: e.target.checked })}
1625
- className="h-4 w-4 rounded border-neutral-700 bg-neutral-950 text-[#3ce6ac] focus:ring-[#3ce6ac]"
1626
- />
1627
- Repeat
1628
- </label>
1629
- <button
1630
- type="button"
1631
- disabled={disabled}
1632
- onClick={() =>
1633
- commit({
1634
- ...parsed,
1635
- stops: [...parsed.stops].reverse().map((stop) => ({
1636
- ...stop,
1637
- position: 100 - stop.position,
1638
- })),
1639
- })
1640
- }
1641
- className="inline-flex h-7 items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white disabled:cursor-not-allowed disabled:text-neutral-600"
1642
- >
1643
- <RotateCcw size={12} />
1644
- Reverse
1645
- </button>
1646
- </div>
1647
- </div>
1648
-
1649
- {(parsed.kind === "linear" || parsed.kind === "conic") && (
1650
- <div className="grid gap-1.5">
1651
- <span className={LABEL}>{parsed.kind === "linear" ? "Angle" : "Start angle"}</span>
1652
- <SliderControl
1653
- value={parsed.angle}
1654
- min={0}
1655
- max={360}
1656
- step={1}
1657
- disabled={disabled}
1658
- displayValue={`${Math.round(parsed.angle)}°`}
1659
- formatDisplayValue={(next) => `${Math.round(next)}°`}
1660
- onCommit={(next) => patch({ angle: next })}
1661
- />
1662
- </div>
1663
- )}
1664
-
1665
- {parsed.kind === "radial" && (
1666
- <div className={RESPONSIVE_GRID}>
1667
- <SelectField
1668
- label="Shape"
1669
- value={parsed.shape}
1670
- disabled={disabled}
1671
- onChange={(next) => patch({ shape: next as GradientModel["shape"] })}
1672
- options={["ellipse", "circle"]}
1673
- />
1674
- <SelectField
1675
- label="Size"
1676
- value={parsed.radialSize}
1677
- disabled={disabled}
1678
- onChange={(next) => patch({ radialSize: next as GradientModel["radialSize"] })}
1679
- options={["closest-side", "closest-corner", "farthest-side", "farthest-corner"]}
1680
- />
1681
- </div>
1682
- )}
1683
-
1684
- {(parsed.kind === "radial" || parsed.kind === "conic") && (
1685
- <div className={RESPONSIVE_GRID}>
1686
- <div className="grid min-w-0 gap-1.5">
1687
- <span className={LABEL}>Center X</span>
1688
- <SliderControl
1689
- value={parsed.centerX}
1690
- min={0}
1691
- max={100}
1692
- step={1}
1693
- disabled={disabled}
1694
- displayValue={`${Math.round(parsed.centerX)}%`}
1695
- formatDisplayValue={(next) => `${Math.round(next)}%`}
1696
- onCommit={(next) => patch({ centerX: next })}
1697
- />
1698
- </div>
1699
- <div className="grid min-w-0 gap-1.5">
1700
- <span className={LABEL}>Center Y</span>
1701
- <SliderControl
1702
- value={parsed.centerY}
1703
- min={0}
1704
- max={100}
1705
- step={1}
1706
- disabled={disabled}
1707
- displayValue={`${Math.round(parsed.centerY)}%`}
1708
- formatDisplayValue={(next) => `${Math.round(next)}%`}
1709
- onCommit={(next) => patch({ centerY: next })}
1710
- />
1711
- </div>
1712
- </div>
1713
- )}
1714
-
1715
- <div className="space-y-3">
1716
- <div className="flex items-center justify-between">
1717
- <span className={LABEL}>Stops</span>
1718
- <button
1719
- type="button"
1720
- disabled={disabled || parsed.stops.length >= 6}
1721
- onClick={() => addStop()}
1722
- className="inline-flex h-7 items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white disabled:cursor-not-allowed disabled:text-neutral-600"
1723
- >
1724
- <Plus size={12} />
1725
- Add stop
1726
- </button>
1727
- </div>
1728
- <div className="space-y-3">
1729
- {parsed.stops.map((stop, index) => (
1730
- <div
1731
- key={`stop-editor-${index}`}
1732
- className="grid min-w-0 grid-cols-[minmax(0,1fr)_68px_28px] gap-2"
1733
- >
1734
- <ColorField
1735
- label={`Stop ${index + 1}`}
1736
- value={stop.color}
1737
- disabled={disabled}
1738
- onCommit={(next) => updateStop(index, { color: next })}
1739
- />
1740
- <DetailField
1741
- label="Pos"
1742
- value={`${Math.round(stop.position)}%`}
1743
- disabled={disabled}
1744
- onCommit={(next) =>
1745
- updateStop(index, {
1746
- position: Number.parseFloat(next.replace("%", "")) || 0,
1747
- })
1748
- }
1749
- />
1750
- <button
1751
- type="button"
1752
- disabled={disabled || parsed.stops.length <= 2}
1753
- onClick={() => removeStop(index)}
1754
- className="mt-[22px] flex h-10 items-center justify-center rounded-lg border border-neutral-700 bg-neutral-950 text-neutral-400 transition-colors hover:border-neutral-600 hover:text-white disabled:cursor-not-allowed disabled:text-neutral-700"
1755
- aria-label={`Remove stop ${index + 1}`}
1756
- >
1757
- <X size={12} />
1758
- </button>
1759
- </div>
1760
- ))}
1761
- </div>
1762
- </div>
1763
- </div>
1764
- );
1765
- }
1766
-
1767
- function SliderControl({
1768
- value,
1769
- min,
1770
- max,
1771
- step,
1772
- displayValue,
1773
- formatDisplayValue,
1774
- disabled,
1775
- onCommit,
1776
- }: {
1777
- value: number;
1778
- min: number;
1779
- max: number;
1780
- step: number;
1781
- displayValue: string;
1782
- formatDisplayValue?: (nextValue: number) => string;
1783
- disabled?: boolean;
1784
- onCommit: (nextValue: number) => void;
24
+ onChange: (v: string) => void;
1785
25
  }) {
1786
- const [draft, setDraft] = useState(value);
1787
- const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
1788
- const valueRef = useRef(value);
1789
-
1790
- valueRef.current = value;
1791
-
1792
- useEffect(() => {
1793
- setDraft(value);
1794
- }, [value]);
1795
-
1796
- useEffect(
1797
- () => () => {
1798
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
1799
- },
1800
- [],
1801
- );
1802
-
1803
- const commitDraft = (nextDraft: number) => {
1804
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
1805
- if (nextDraft !== valueRef.current) {
1806
- onCommit(nextDraft);
1807
- }
1808
- };
1809
-
1810
- const scheduleCommit = (nextDraft: number) => {
1811
- if (commitTimerRef.current) clearTimeout(commitTimerRef.current);
1812
- commitTimerRef.current = setTimeout(() => {
1813
- if (nextDraft !== valueRef.current) {
1814
- onCommit(nextDraft);
1815
- }
1816
- }, 40);
1817
- };
1818
-
1819
- const renderedDisplayValue = formatDisplayValue?.(draft) ?? displayValue;
1820
-
1821
26
  return (
1822
- <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2">
27
+ <div className="flex items-center gap-2">
28
+ <span className="text-2xs text-neutral-600 w-16 flex-shrink-0 text-right">{label}</span>
1823
29
  <input
1824
- type="range"
1825
- min={min}
1826
- max={max}
1827
- step={step}
1828
- value={draft}
1829
- disabled={disabled}
1830
- onChange={(e) => {
1831
- const nextDraft = Number(e.target.value);
1832
- setDraft(nextDraft);
1833
- scheduleCommit(nextDraft);
1834
- }}
1835
- onMouseUp={() => commitDraft(draft)}
1836
- onTouchEnd={() => commitDraft(draft)}
1837
- onBlur={() => commitDraft(draft)}
1838
- className="h-2 min-w-0 w-full cursor-pointer appearance-none rounded-full bg-neutral-800 accent-[#3ce6ac] disabled:cursor-not-allowed"
30
+ type="text"
31
+ value={value}
32
+ onChange={(e) => onChange(e.target.value)}
33
+ className="flex-1 bg-neutral-900 border border-neutral-800 rounded px-1.5 py-0.5 text-2xs text-neutral-200 font-mono outline-none focus:border-neutral-600 min-w-0"
1839
34
  />
1840
- <div className="min-w-[52px] rounded-xl border border-neutral-800 bg-neutral-900 px-2 py-2 text-right text-[11px] font-medium text-neutral-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]">
1841
- {renderedDisplayValue}
1842
- </div>
1843
35
  </div>
1844
36
  );
1845
37
  }
1846
38
 
1847
- function SegmentedControl({
1848
- options,
1849
- value,
1850
- disabled,
1851
- onChange,
1852
- }: {
1853
- options: Array<{ label: string; value: string }>;
1854
- value: string;
1855
- disabled?: boolean;
1856
- onChange: (nextValue: string) => void;
1857
- }) {
1858
- return (
1859
- <div
1860
- className="grid min-w-0 gap-1 rounded-xl bg-neutral-900 p-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]"
1861
- style={{ gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}
1862
- >
1863
- {options.map((option) => {
1864
- const selected = option.value === value;
1865
- return (
1866
- <button
1867
- key={option.value}
1868
- type="button"
1869
- disabled={disabled}
1870
- onClick={() => onChange(option.value)}
1871
- className={`min-w-0 truncate rounded-lg px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${
1872
- selected
1873
- ? "bg-neutral-800 text-white shadow-[0_1px_3px_rgba(0,0,0,0.28)]"
1874
- : "text-neutral-500 hover:text-neutral-200"
1875
- }`}
1876
- >
1877
- {option.label}
1878
- </button>
1879
- );
1880
- })}
1881
- </div>
1882
- );
1883
- }
1884
-
1885
- function SelectField({
39
+ function ColorRow({
1886
40
  label,
1887
41
  value,
1888
- disabled,
1889
- options,
1890
42
  onChange,
1891
43
  }: {
1892
44
  label: string;
1893
45
  value: string;
1894
- disabled?: boolean;
1895
- options: string[];
1896
- onChange: (nextValue: string) => void;
46
+ onChange: (v: string) => void;
1897
47
  }) {
1898
48
  return (
1899
- <label className="grid min-w-0 gap-1.5">
1900
- <span className={LABEL}>{label}</span>
1901
- <div className={FIELD}>
1902
- <select
49
+ <div className="flex items-center gap-2">
50
+ <span className="text-2xs text-neutral-600 w-16 flex-shrink-0 text-right">{label}</span>
51
+ <div className="flex items-center gap-1 flex-1">
52
+ <div
53
+ className="w-5 h-5 rounded border border-neutral-700 flex-shrink-0"
54
+ style={{ backgroundColor: value }}
55
+ />
56
+ <input
57
+ type="text"
1903
58
  value={value}
1904
- disabled={disabled}
1905
59
  onChange={(e) => onChange(e.target.value)}
1906
- className="min-w-0 w-full appearance-none bg-transparent text-[11px] font-medium text-neutral-100 outline-none disabled:cursor-not-allowed disabled:text-neutral-600"
1907
- >
1908
- {options.map((option) => (
1909
- <option key={option} value={option}>
1910
- {option}
1911
- </option>
1912
- ))}
1913
- </select>
1914
- </div>
1915
- </label>
1916
- );
1917
- }
1918
-
1919
- function Section({
1920
- title,
1921
- icon,
1922
- children,
1923
- accessory,
1924
- }: {
1925
- title: string;
1926
- icon: ReactNode;
1927
- children: ReactNode;
1928
- accessory?: ReactNode;
1929
- }) {
1930
- return (
1931
- <section className="min-w-0 border-t border-neutral-800/80 px-4 py-4">
1932
- <div className="mb-3 flex min-w-0 flex-wrap items-center justify-between gap-2">
1933
- <div className="flex min-w-0 items-center gap-2.5">
1934
- <span className="flex-shrink-0 text-neutral-500">{icon}</span>
1935
- <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-neutral-300">
1936
- {title}
1937
- </h3>
1938
- </div>
1939
- {accessory}
60
+ className="flex-1 bg-neutral-900 border border-neutral-800 rounded px-1.5 py-0.5 text-2xs text-neutral-200 font-mono outline-none focus:border-neutral-600 min-w-0"
61
+ />
1940
62
  </div>
1941
- {children}
1942
- </section>
63
+ </div>
1943
64
  );
1944
65
  }
1945
66
 
1946
- function SelectionColorRow({
1947
- swatch,
1948
- token,
1949
- sources,
1950
- }: {
1951
- swatch: string;
1952
- token: string;
1953
- sources: string[];
1954
- }) {
67
+ function SectionHeader({ icon: Icon, label }: { icon: typeof Move; label: string }) {
1955
68
  return (
1956
- <div className={`${FIELD} flex min-w-0 items-center gap-3`}>
1957
- <div
1958
- className="h-7 w-7 flex-shrink-0 rounded-lg border border-neutral-700"
1959
- style={{ backgroundColor: swatch }}
1960
- />
1961
- <div className="min-w-0 flex-1">
1962
- <div className="truncate text-[11px] font-medium text-neutral-100">{token}</div>
1963
- <div className="truncate text-[11px] uppercase tracking-[0.18em] text-neutral-500">
1964
- {sources.join(" · ")}
1965
- </div>
1966
- </div>
69
+ <div className="flex items-center gap-1.5 mt-2 mb-1">
70
+ <Icon size={10} className="text-neutral-600" />
71
+ <span className="text-2xs font-medium text-neutral-500 uppercase tracking-wider">
72
+ {label}
73
+ </span>
1967
74
  </div>
1968
75
  );
1969
76
  }
1970
77
 
1971
78
  export const PropertyPanel = memo(function PropertyPanel({
1972
- projectId,
1973
- assets,
1974
79
  element,
1975
- copiedAgentPrompt,
1976
- onClearSelection,
80
+ isPickMode,
81
+ onEnablePick,
82
+ onDisablePick,
83
+ onClearPick,
1977
84
  onSetStyle,
85
+ onSetDataAttr,
1978
86
  onSetText,
1979
- onSetTextFieldStyle,
1980
- onAddTextField,
1981
- onRemoveTextField,
1982
- onDetachFromLayout,
1983
- onAskAgent,
1984
- onCopyAgentInstruction,
1985
- onImportAssets,
1986
- fontAssets = [],
1987
- onImportFonts,
1988
- allowLayoutDetach = true,
1989
87
  }: PropertyPanelProps) {
1990
- const styles = element?.computedStyles ?? EMPTY_STYLES;
1991
- const selectionColors = useMemo(() => collectSelectionColors(styles), [styles]);
1992
- const backgroundImage = styles["background-image"] ?? "none";
1993
- const fillMode =
1994
- backgroundImage && backgroundImage !== "none"
1995
- ? backgroundImage.includes("gradient")
1996
- ? "Gradient"
1997
- : "Image"
1998
- : "Solid";
1999
- const [preferredFillMode, setPreferredFillMode] = useState(fillMode);
2000
- const imageUrl = extractBackgroundImageUrl(backgroundImage);
2001
- const [activeTextFieldKey, setActiveTextFieldKey] = useState<string | null>(
2002
- element?.textFields[0]?.key ?? null,
2003
- );
2004
- const hasTextControls = element != null && isTextEditableSelection(element);
2005
-
2006
- useEffect(() => {
2007
- setPreferredFillMode(fillMode);
2008
- }, [fillMode, element?.id, element?.selector, backgroundImage]);
2009
-
2010
- useEffect(() => {
2011
- const nextFields = element?.textFields ?? [];
2012
- setActiveTextFieldKey((current) => {
2013
- if (current && nextFields.some((field) => field.key === current)) return current;
2014
- return nextFields[0]?.key ?? null;
2015
- });
2016
- }, [element?.id, element?.selector, element?.textFields]);
2017
-
2018
88
  if (!element) {
2019
89
  return (
2020
- <div className="flex h-full flex-col items-center justify-center bg-neutral-900 px-6 text-center">
2021
- <Eye size={18} className="mb-3 text-neutral-600" />
2022
- <p className="text-sm font-medium text-neutral-200">Select an element in the preview.</p>
2023
- <p className="mt-2 max-w-[260px] text-xs leading-5 text-neutral-500">
2024
- The inspector is tuned for direct DOM edits with safer geometry controls, color picking,
2025
- and cleaner grouped layer controls.
2026
- </p>
90
+ <div className="flex flex-col items-center justify-center h-full px-4 text-center">
91
+ <MousePointer size={20} className="text-neutral-700 mb-2" />
92
+ <p className="text-xs text-neutral-500">Click an element in the preview to inspect it</p>
93
+ <Button
94
+ variant="secondary"
95
+ size="sm"
96
+ onClick={isPickMode ? onDisablePick : onEnablePick}
97
+ className={`mt-3 ${isPickMode ? "bg-studio-accent/20 text-studio-accent border-studio-accent/30" : ""}`}
98
+ >
99
+ {isPickMode ? "Pick mode active..." : "Enable Pick Mode"}
100
+ </Button>
2027
101
  </div>
2028
102
  );
2029
103
  }
2030
104
 
2031
- const styleEditingDisabled = !element.capabilities.canEditStyles;
2032
- const moveEditingDisabled = !element.capabilities.canMove;
2033
- const resizeEditingDisabled = !element.capabilities.canResize;
2034
- const isFlex = styles.display === "flex" || styles.display === "inline-flex";
2035
- const radiusValue = parseNumericValue(styles["border-radius"]) ?? 0;
2036
- const opacityValue = Math.round((parseNumericValue(styles.opacity) ?? 1) * 100);
2037
- const clipContent = ["hidden", "clip"].includes((styles.overflow ?? "").trim());
2038
- const sourceLabel = element.id ? `#${element.id}` : element.selector;
2039
- const showEditableSections = element.capabilities.canEditStyles;
2040
- const disabledMoveReason =
2041
- allowLayoutDetach &&
2042
- element.capabilities.reasonIfDisabled &&
2043
- !element.capabilities.canDetachFromLayout
2044
- ? element.capabilities.reasonIfDisabled
2045
- : null;
2046
-
2047
- const handleFillModeChange = (nextMode: string) => {
2048
- setPreferredFillMode(nextMode);
2049
- if (nextMode === "Solid") {
2050
- onSetStyle("background-image", "none");
2051
- return;
2052
- }
2053
- if (nextMode === "Gradient" && !backgroundImage.includes("gradient")) {
2054
- onSetStyle(
2055
- "background-image",
2056
- serializeGradient(buildDefaultGradientModel(styles["background-color"])),
2057
- );
2058
- }
2059
- };
105
+ const s = element.computedStyles;
2060
106
 
2061
107
  return (
2062
- <div className="flex h-full min-h-0 flex-col overflow-hidden bg-neutral-900 text-neutral-100">
2063
- <div className="border-b border-neutral-800 px-4 py-5">
2064
- <div className="flex items-start justify-between gap-4">
2065
- <div className="min-w-0">
2066
- <div className={LABEL}>Document</div>
2067
- <div className="mt-3 truncate text-[12px] font-semibold text-neutral-100">
2068
- {element.label}
2069
- </div>
2070
- <div className="mt-1 truncate text-[11px] text-neutral-500">{sourceLabel}</div>
2071
- </div>
2072
- <button
2073
- type="button"
108
+ <div className="flex flex-col h-full min-h-0">
109
+ {/* Header */}
110
+ <div className="flex items-center justify-between px-3 py-2 border-b border-neutral-800 flex-shrink-0">
111
+ <div className="flex items-center gap-1.5 min-w-0">
112
+ <span className="text-2xs font-mono text-studio-accent truncate">{element.selector}</span>
113
+ </div>
114
+ <div className="flex items-center gap-1">
115
+ <IconButton
116
+ icon={<MousePointer size={11} />}
117
+ aria-label={isPickMode ? "Disable pick mode" : "Enable pick mode"}
118
+ size="sm"
119
+ onClick={isPickMode ? onDisablePick : onEnablePick}
120
+ className={isPickMode ? "text-studio-accent bg-studio-accent/10" : ""}
121
+ />
122
+ <IconButton
123
+ icon={<X size={11} />}
2074
124
  aria-label="Clear selection"
2075
- onClick={onClearSelection}
2076
- className="flex h-9 w-9 items-center justify-center rounded-full border border-neutral-700 bg-neutral-950 text-neutral-500 shadow-[0_1px_2px_rgba(0,0,0,0.2)] transition-colors hover:border-neutral-600 hover:text-neutral-200"
2077
- >
2078
- <X size={13} />
2079
- </button>
125
+ size="sm"
126
+ onClick={onClearPick}
127
+ />
2080
128
  </div>
2081
- <button
2082
- type="button"
2083
- onClick={onAskAgent}
2084
- className="mt-4 inline-flex h-8 items-center justify-center gap-2 rounded-xl border border-neutral-700 bg-neutral-950 px-3.5 text-[11px] font-medium text-neutral-100 transition-colors hover:border-studio-accent/40 hover:text-studio-accent"
2085
- >
2086
- <MessageSquare size={15} />
2087
- <span>{copiedAgentPrompt ? "Prompt copied" : "Ask agent"}</span>
2088
- </button>
2089
129
  </div>
2090
130
 
2091
- <div className="flex-1 overflow-y-auto">
2092
- <Section title="Layout" icon={<Move size={15} />}>
2093
- <div className={RESPONSIVE_GRID}>
2094
- <MetricField
2095
- label="X"
2096
- value={styles.left ?? "auto"}
2097
- disabled={moveEditingDisabled}
2098
- onCommit={(next) => onSetStyle("left", next)}
2099
- />
2100
- <MetricField
2101
- label="Y"
2102
- value={styles.top ?? "auto"}
2103
- disabled={moveEditingDisabled}
2104
- onCommit={(next) => onSetStyle("top", next)}
131
+ {/* Properties */}
132
+ <div className="flex-1 overflow-y-auto px-3 py-2 space-y-1">
133
+ {/* Element info */}
134
+ <div className="flex items-center gap-2 mb-2">
135
+ <span className="text-2xs text-neutral-300 font-medium">{element.label}</span>
136
+ <span className="text-2xs text-neutral-600 font-mono">&lt;{element.tagName}&gt;</span>
137
+ </div>
138
+
139
+ {/* Position & Size */}
140
+ <SectionHeader icon={Move} label="Position & Size" />
141
+ <div className="grid grid-cols-2 gap-1">
142
+ <PropertyRow
143
+ label="X"
144
+ value={s["left"] ?? "auto"}
145
+ onChange={(v) => onSetStyle("left", v)}
146
+ />
147
+ <PropertyRow
148
+ label="Y"
149
+ value={s["top"] ?? "auto"}
150
+ onChange={(v) => onSetStyle("top", v)}
151
+ />
152
+ <PropertyRow
153
+ label="W"
154
+ value={s["width"] ?? "auto"}
155
+ onChange={(v) => onSetStyle("width", v)}
156
+ />
157
+ <PropertyRow
158
+ label="H"
159
+ value={s["height"] ?? "auto"}
160
+ onChange={(v) => onSetStyle("height", v)}
161
+ />
162
+ </div>
163
+
164
+ {/* Typography */}
165
+ {(element.tagName === "div" ||
166
+ element.tagName === "span" ||
167
+ element.tagName === "p" ||
168
+ element.tagName === "h1" ||
169
+ element.tagName === "h2") && (
170
+ <>
171
+ <SectionHeader icon={Type} label="Typography" />
172
+ <PropertyRow
173
+ label="Size"
174
+ value={s["font-size"] ?? ""}
175
+ onChange={(v) => onSetStyle("font-size", v)}
2105
176
  />
2106
- <MetricField
2107
- label="W"
2108
- value={styles.width ?? "auto"}
2109
- disabled={resizeEditingDisabled}
2110
- onCommit={(next) => onSetStyle("width", next)}
177
+ <PropertyRow
178
+ label="Weight"
179
+ value={s["font-weight"] ?? ""}
180
+ onChange={(v) => onSetStyle("font-weight", v)}
2111
181
  />
2112
- <MetricField
2113
- label="H"
2114
- value={styles.height ?? "auto"}
2115
- disabled={resizeEditingDisabled}
2116
- onCommit={(next) => onSetStyle("height", next)}
182
+ <PropertyRow
183
+ label="Family"
184
+ value={s["font-family"]?.split(",")[0] ?? ""}
185
+ onChange={(v) => onSetStyle("font-family", v)}
2117
186
  />
2118
- </div>
2119
- {disabledMoveReason && (
2120
- <div className="mt-4 flex min-w-0 flex-wrap items-center justify-between gap-3 border-l border-amber-500/40 pl-3">
2121
- <div className="min-w-0 text-[11px] leading-5 text-neutral-400">
2122
- <div className="font-medium text-amber-100">{disabledMoveReason}</div>
2123
- <div>Copy a targeted prompt so an agent can refactor this layer safely.</div>
2124
- </div>
2125
- <button
2126
- type="button"
2127
- onClick={() => {
2128
- void Promise.resolve(
2129
- onCopyAgentInstruction(buildMakeMovableAgentInstruction(disabledMoveReason)),
2130
- );
2131
- }}
2132
- className="inline-flex h-8 flex-shrink-0 items-center rounded-lg border border-neutral-700 bg-neutral-950 px-3 text-[11px] font-medium text-neutral-100 transition-colors hover:border-amber-400/70 hover:text-amber-100"
2133
- >
2134
- {copiedAgentPrompt ? "Prompt copied" : "Ask agent to make movable"}
2135
- </button>
2136
- </div>
2137
- )}
2138
- {allowLayoutDetach && element.capabilities.canDetachFromLayout && (
2139
- <div className="mt-4 flex min-w-0 flex-wrap items-center justify-between gap-3 border-l border-amber-500/40 pl-3">
2140
- <div className="min-w-0 text-[11px] leading-5 text-neutral-400">
2141
- <div className="font-medium text-neutral-200">
2142
- This layer is controlled by layout.
2143
- </div>
2144
- <div>Detaches from flex/grid flow and preserves current visual position.</div>
2145
- </div>
2146
- <button
2147
- type="button"
2148
- onClick={onDetachFromLayout}
2149
- className="inline-flex h-8 flex-shrink-0 items-center rounded-lg border border-neutral-700 bg-neutral-950 px-3 text-[11px] font-medium text-neutral-100 transition-colors hover:border-amber-400/70 hover:text-amber-100"
2150
- >
2151
- Make movable
2152
- </button>
2153
- </div>
2154
- )}
2155
- </Section>
2156
-
2157
- {showEditableSections && isFlex && (
2158
- <Section title="Flex" icon={<Layers size={15} />}>
2159
- <div className="space-y-4">
2160
- <SegmentedControl
2161
- disabled={styleEditingDisabled}
2162
- value={styles["flex-direction"] || "row"}
2163
- onChange={(next) => onSetStyle("flex-direction", next)}
2164
- options={[
2165
- { label: "→ Row", value: "row" },
2166
- { label: "↓ Column", value: "column" },
2167
- ]}
2168
- />
2169
- <div className={RESPONSIVE_GRID}>
2170
- <SelectField
2171
- label="Justify"
2172
- value={styles["justify-content"] || "flex-start"}
2173
- disabled={styleEditingDisabled}
2174
- onChange={(next) => onSetStyle("justify-content", next)}
2175
- options={[
2176
- "flex-start",
2177
- "center",
2178
- "space-between",
2179
- "space-around",
2180
- "space-evenly",
2181
- "flex-end",
2182
- ]}
2183
- />
2184
- <SelectField
2185
- label="Align"
2186
- value={styles["align-items"] || "stretch"}
2187
- disabled={styleEditingDisabled}
2188
- onChange={(next) => onSetStyle("align-items", next)}
2189
- options={["stretch", "flex-start", "center", "flex-end", "baseline"]}
2190
- />
2191
- </div>
2192
- <DetailField
2193
- label="Gap"
2194
- value={styles.gap ?? "0px"}
2195
- disabled={styleEditingDisabled}
2196
- onCommit={(next) => onSetStyle("gap", next.endsWith("px") ? next : `${next}px`)}
2197
- />
2198
- <label className="flex items-center gap-3 rounded-2xl border border-neutral-800 bg-neutral-900 px-3 py-3 text-[12px] text-neutral-300 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]">
2199
- <input
2200
- type="checkbox"
2201
- checked={clipContent}
2202
- disabled={styleEditingDisabled}
2203
- onChange={(e) => onSetStyle("overflow", e.target.checked ? "hidden" : "visible")}
2204
- className="h-4 w-4 rounded border-neutral-700 bg-neutral-950 text-[#3ce6ac] focus:ring-[#3ce6ac]"
2205
- />
2206
- <span>Clip content</span>
2207
- </label>
2208
- </div>
2209
- </Section>
187
+ </>
2210
188
  )}
2211
189
 
2212
- {showEditableSections && (
2213
- <>
2214
- <Section title="Radius" icon={<Settings size={15} />}>
2215
- <SliderControl
2216
- value={radiusValue}
2217
- min={0}
2218
- max={Math.max(240, Math.ceil(radiusValue))}
2219
- step={1}
2220
- disabled={styleEditingDisabled}
2221
- displayValue={`${formatNumericValue(radiusValue)}px`}
2222
- formatDisplayValue={(next) => `${formatNumericValue(next)}px`}
2223
- onCommit={(next) => onSetStyle("border-radius", `${formatNumericValue(next)}px`)}
2224
- />
2225
- </Section>
2226
-
2227
- <Section title="Blending" icon={<Eye size={15} />}>
2228
- <div className="space-y-4">
2229
- <SliderControl
2230
- value={opacityValue}
2231
- min={0}
2232
- max={100}
2233
- step={1}
2234
- disabled={styleEditingDisabled}
2235
- displayValue={`${opacityValue}%`}
2236
- formatDisplayValue={(next) => `${Math.round(next)}%`}
2237
- onCommit={(next) => onSetStyle("opacity", formatNumericValue(next / 100))}
2238
- />
2239
- <SelectField
2240
- label="Mode"
2241
- value={styles["mix-blend-mode"] || "normal"}
2242
- disabled={styleEditingDisabled}
2243
- onChange={(next) => onSetStyle("mix-blend-mode", next)}
2244
- options={["normal", "multiply", "screen", "overlay", "darken", "lighten"]}
2245
- />
2246
- </div>
2247
- </Section>
2248
-
2249
- <Section
2250
- title="Fill"
2251
- icon={<Palette size={15} />}
2252
- accessory={
2253
- <div className="rounded-full border border-neutral-700 bg-neutral-900 px-2.5 py-1 text-[10px] font-medium uppercase tracking-[0.16em] text-neutral-400">
2254
- {preferredFillMode}
2255
- </div>
2256
- }
2257
- >
2258
- <div className="space-y-4">
2259
- <SegmentedControl
2260
- disabled={styleEditingDisabled}
2261
- value={preferredFillMode}
2262
- onChange={handleFillModeChange}
2263
- options={[
2264
- { label: "Solid", value: "Solid" },
2265
- { label: "Gradient", value: "Gradient" },
2266
- { label: "Image", value: "Image" },
2267
- ]}
2268
- />
2269
- {preferredFillMode === "Solid" ? (
2270
- <ColorField
2271
- label="Fill color"
2272
- value={styles["background-color"] ?? "transparent"}
2273
- disabled={styleEditingDisabled}
2274
- onCommit={(next) => onSetStyle("background-color", next)}
2275
- />
2276
- ) : preferredFillMode === "Gradient" ? (
2277
- <GradientField
2278
- value={
2279
- backgroundImage !== "none"
2280
- ? backgroundImage
2281
- : serializeGradient(buildDefaultGradientModel(styles["background-color"]))
2282
- }
2283
- fallbackColor={styles["background-color"]}
2284
- disabled={styleEditingDisabled}
2285
- onCommit={(next) => onSetStyle("background-image", next)}
2286
- />
2287
- ) : (
2288
- <ImageFillField
2289
- projectId={projectId}
2290
- sourceFile={element.sourceFile}
2291
- value={imageUrl}
2292
- assets={assets}
2293
- disabled={styleEditingDisabled}
2294
- onCommit={(next) => onSetStyle("background-image", next)}
2295
- onImportAssets={onImportAssets}
2296
- />
2297
- )}
2298
- {!hasTextControls && (
2299
- <ColorField
2300
- label="Text color"
2301
- value={styles.color ?? "rgb(0, 0, 0)"}
2302
- disabled={styleEditingDisabled}
2303
- onCommit={(next) => onSetStyle("color", next)}
2304
- />
2305
- )}
2306
- </div>
2307
- </Section>
2308
-
2309
- {hasTextControls && (
2310
- <Section title="Text" icon={<Type size={15} />}>
2311
- {(() => {
2312
- const textFields = element.textFields;
2313
- const activeField =
2314
- textFields.find((field) => field.key === activeTextFieldKey) ?? textFields[0];
2315
- if (!activeField) return null;
2316
-
2317
- if (textFields.length === 1) {
2318
- return (
2319
- <div className="space-y-4 rounded-xl border border-neutral-800 bg-neutral-900/60 p-3">
2320
- <div className="min-w-0">
2321
- <div className="truncate text-[11px] font-medium text-neutral-100">
2322
- {formatTextFieldPreview(activeField.value) || "Text"}
2323
- </div>
2324
- <div className="text-[10px] uppercase tracking-[0.12em] text-neutral-500">
2325
- {activeField.tagName}
2326
- </div>
2327
- </div>
2328
-
2329
- <TextAreaField
2330
- key={activeField.key}
2331
- label="Content"
2332
- value={activeField.value}
2333
- disabled={false}
2334
- onCommit={(next) => onSetText(next, activeField.key)}
2335
- />
2336
-
2337
- <ColorField
2338
- label="Text color"
2339
- value={getTextFieldColor(activeField, styles)}
2340
- disabled={false}
2341
- onCommit={(next) => onSetTextFieldStyle(activeField.key, "color", next)}
2342
- />
2343
-
2344
- <div className={RESPONSIVE_GRID}>
2345
- <MetricField
2346
- label="Size"
2347
- value={
2348
- activeField.computedStyles["font-size"] ||
2349
- styles["font-size"] ||
2350
- "16px"
2351
- }
2352
- disabled={false}
2353
- liveCommit
2354
- onCommit={(next) =>
2355
- onSetTextFieldStyle(activeField.key, "font-size", next)
2356
- }
2357
- />
2358
- <FontWeightField
2359
- value={
2360
- activeField.computedStyles["font-weight"] ||
2361
- styles["font-weight"] ||
2362
- "400"
2363
- }
2364
- disabled={false}
2365
- onCommit={(next) =>
2366
- onSetTextFieldStyle(activeField.key, "font-weight", next)
2367
- }
2368
- />
2369
- </div>
2370
-
2371
- <FontFamilyField
2372
- value={
2373
- activeField.computedStyles["font-family"] ||
2374
- styles["font-family"] ||
2375
- "inherit"
2376
- }
2377
- disabled={false}
2378
- importedFonts={fontAssets}
2379
- onImportFonts={onImportFonts}
2380
- onCommit={(next) =>
2381
- onSetTextFieldStyle(activeField.key, "font-family", next)
2382
- }
2383
- />
2384
- </div>
2385
- );
2386
- }
2387
-
2388
- return (
2389
- <div className="space-y-4">
2390
- <div className="grid gap-1.5">
2391
- <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
2392
- <span className={LABEL}>Text layers</span>
2393
- <button
2394
- type="button"
2395
- onClick={() => {
2396
- void Promise.resolve(onAddTextField(activeField.key)).then(
2397
- (nextKey) => {
2398
- if (nextKey) setActiveTextFieldKey(nextKey);
2399
- },
2400
- );
2401
- }}
2402
- className="inline-flex h-7 max-w-full items-center gap-1.5 rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white"
2403
- >
2404
- <Plus size={12} className="flex-shrink-0" />
2405
- <span className="truncate">Add text</span>
2406
- </button>
2407
- </div>
2408
- <div className="grid gap-2">
2409
- {textFields.map((field, index) => {
2410
- const active = field.key === activeField.key;
2411
- return (
2412
- <button
2413
- key={field.key}
2414
- type="button"
2415
- onClick={() => setActiveTextFieldKey(field.key)}
2416
- className={`min-w-0 w-full rounded-xl border px-3 py-2 text-left transition-colors ${
2417
- active
2418
- ? "border-studio-accent/50 bg-studio-accent/10"
2419
- : "border-neutral-800 bg-neutral-900/80 hover:border-neutral-700 hover:bg-neutral-900"
2420
- }`}
2421
- >
2422
- <div className="flex min-w-0 items-center justify-between gap-2">
2423
- <div className="flex min-w-0 items-center gap-2">
2424
- <span
2425
- className="h-4 w-4 flex-shrink-0 rounded border border-neutral-700 bg-neutral-950"
2426
- style={{ backgroundColor: getTextFieldColor(field, styles) }}
2427
- />
2428
- <span className="min-w-0 truncate text-[11px] font-medium text-neutral-100">
2429
- {formatTextFieldPreview(field.value) || `Text ${index + 1}`}
2430
- </span>
2431
- </div>
2432
- <span className="flex-shrink-0 rounded-md border border-neutral-700 bg-neutral-950 px-1.5 py-0.5 text-[10px] uppercase tracking-[0.12em] text-neutral-500">
2433
- {field.tagName}
2434
- </span>
2435
- </div>
2436
- </button>
2437
- );
2438
- })}
2439
- </div>
2440
- </div>
2441
-
2442
- <div className="space-y-4 rounded-xl border border-neutral-800 bg-neutral-900/60 p-3">
2443
- <div className="flex min-w-0 items-center justify-between gap-2">
2444
- <div className="min-w-0">
2445
- <div className="truncate text-[11px] font-medium text-neutral-100">
2446
- {formatTextFieldPreview(activeField.value) || "Text"}
2447
- </div>
2448
- <div className="text-[10px] uppercase tracking-[0.12em] text-neutral-500">
2449
- {activeField.tagName}
2450
- </div>
2451
- </div>
2452
- <button
2453
- type="button"
2454
- onClick={() => onRemoveTextField(activeField.key)}
2455
- className="inline-flex h-7 flex-shrink-0 items-center rounded-lg border border-neutral-700 bg-neutral-950 px-2.5 text-[11px] font-medium text-neutral-300 transition-colors hover:border-neutral-600 hover:text-white"
2456
- >
2457
- Remove
2458
- </button>
2459
- </div>
2460
-
2461
- <TextAreaField
2462
- key={activeField.key}
2463
- label="Content"
2464
- value={activeField.value}
2465
- disabled={false}
2466
- autoFocus
2467
- onCommit={(next) => onSetText(next, activeField.key)}
2468
- />
2469
-
2470
- <ColorField
2471
- label="Text color"
2472
- value={getTextFieldColor(activeField, styles)}
2473
- disabled={false}
2474
- onCommit={(next) => onSetTextFieldStyle(activeField.key, "color", next)}
2475
- />
190
+ {/* Colors */}
191
+ <SectionHeader icon={Palette} label="Colors" />
192
+ <ColorRow
193
+ label="Color"
194
+ value={s["color"] ?? "#fff"}
195
+ onChange={(v) => onSetStyle("color", v)}
196
+ />
197
+ <ColorRow
198
+ label="Background"
199
+ value={s["background-color"] ?? "transparent"}
200
+ onChange={(v) => onSetStyle("background-color", v)}
201
+ />
2476
202
 
2477
- <div className={RESPONSIVE_GRID}>
2478
- <MetricField
2479
- label="Size"
2480
- value={activeField.computedStyles["font-size"] || "16px"}
2481
- disabled={false}
2482
- liveCommit
2483
- onCommit={(next) =>
2484
- onSetTextFieldStyle(activeField.key, "font-size", next)
2485
- }
2486
- />
2487
- <FontWeightField
2488
- value={activeField.computedStyles["font-weight"] || "400"}
2489
- disabled={false}
2490
- onCommit={(next) =>
2491
- onSetTextFieldStyle(activeField.key, "font-weight", next)
2492
- }
2493
- />
2494
- </div>
203
+ {/* Appearance */}
204
+ <SectionHeader icon={Eye} label="Appearance" />
205
+ <PropertyRow
206
+ label="Opacity"
207
+ value={s["opacity"] ?? "1"}
208
+ onChange={(v) => onSetStyle("opacity", v)}
209
+ />
210
+ <PropertyRow
211
+ label="Radius"
212
+ value={s["border-radius"] ?? "0"}
213
+ onChange={(v) => onSetStyle("border-radius", v)}
214
+ />
215
+ <PropertyRow
216
+ label="Z-index"
217
+ value={s["z-index"] ?? "auto"}
218
+ onChange={(v) => onSetStyle("z-index", v)}
219
+ />
220
+ <PropertyRow
221
+ label="Transform"
222
+ value={s["transform"] ?? "none"}
223
+ onChange={(v) => onSetStyle("transform", v)}
224
+ />
2495
225
 
2496
- <FontFamilyField
2497
- value={
2498
- activeField.computedStyles["font-family"] ||
2499
- styles["font-family"] ||
2500
- "inherit"
2501
- }
2502
- disabled={false}
2503
- importedFonts={fontAssets}
2504
- onImportFonts={onImportFonts}
2505
- onCommit={(next) =>
2506
- onSetTextFieldStyle(activeField.key, "font-family", next)
2507
- }
2508
- />
2509
- </div>
2510
- </div>
2511
- );
2512
- })()}
2513
- </Section>
226
+ {/* Timing */}
227
+ {(element.dataAttributes["start"] || element.dataAttributes["duration"]) && (
228
+ <>
229
+ <SectionHeader icon={Clock} label="Timing" />
230
+ {element.dataAttributes["start"] != null && (
231
+ <PropertyRow
232
+ label="Start"
233
+ value={element.dataAttributes["start"]}
234
+ onChange={(v) => onSetDataAttr("start", v)}
235
+ />
2514
236
  )}
2515
-
2516
- {selectionColors.length > 0 && (
2517
- <Section title="Selection colors" icon={<Palette size={15} />}>
2518
- <div className="space-y-3">
2519
- {selectionColors.map((entry) => (
2520
- <SelectionColorRow
2521
- key={`${entry.swatch}-${entry.token}`}
2522
- swatch={entry.swatch}
2523
- token={entry.token}
2524
- sources={entry.sources}
2525
- />
2526
- ))}
2527
- </div>
2528
- </Section>
237
+ {element.dataAttributes["duration"] != null && (
238
+ <PropertyRow
239
+ label="Duration"
240
+ value={element.dataAttributes["duration"]}
241
+ onChange={(v) => onSetDataAttr("duration", v)}
242
+ />
2529
243
  )}
244
+ {element.dataAttributes["track-index"] != null && (
245
+ <PropertyRow
246
+ label="Track"
247
+ value={element.dataAttributes["track-index"]}
248
+ onChange={(v) => onSetDataAttr("track-index", v)}
249
+ />
250
+ )}
251
+ </>
252
+ )}
253
+
254
+ {/* Editable text content */}
255
+ {element.textContent && (
256
+ <>
257
+ <SectionHeader icon={Type} label="Text Content" />
258
+ <textarea
259
+ defaultValue={element.textContent}
260
+ onBlur={(e) => onSetText?.(e.target.value)}
261
+ onKeyDown={(e) => {
262
+ if (e.key === "Enter" && e.metaKey) {
263
+ (e.target as HTMLTextAreaElement).blur();
264
+ }
265
+ }}
266
+ rows={3}
267
+ className="w-full bg-neutral-900 border border-neutral-800 rounded px-2 py-1.5 text-xs text-neutral-200 outline-none focus:border-neutral-600 resize-y leading-relaxed"
268
+ placeholder="Edit text..."
269
+ />
2530
270
  </>
2531
271
  )}
2532
272
  </div>