@hyperframes/studio 0.5.7 → 0.6.0-alpha.10

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