@hyperframes/studio 0.6.0-alpha.12 → 0.6.0-alpha.14

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 (61) hide show
  1. package/dist/assets/hyperframes-player-BI1oj9hu.js +418 -0
  2. package/dist/assets/index-CBj2NLRG.js +117 -0
  3. package/dist/assets/index-D1JDq7Gg.css +1 -0
  4. package/dist/favicon.svg +14 -0
  5. package/dist/index.html +3 -2
  6. package/package.json +9 -9
  7. package/src/App.tsx +427 -4487
  8. package/src/components/AskAgentModal.tsx +120 -0
  9. package/src/components/StudioHeader.tsx +133 -0
  10. package/src/components/StudioLeftSidebar.tsx +125 -0
  11. package/src/components/StudioPreviewArea.tsx +163 -0
  12. package/src/components/StudioRightPanel.tsx +198 -0
  13. package/src/components/TimelineToolbar.tsx +89 -0
  14. package/src/components/editor/DomEditOverlay.tsx +15 -1
  15. package/src/components/editor/PropertyPanel.tsx +129 -2681
  16. package/src/components/editor/domEditing.ts +38 -5
  17. package/src/components/editor/manualEditingAvailability.test.ts +2 -2
  18. package/src/components/editor/manualEditingAvailability.ts +1 -1
  19. package/src/components/editor/manualEdits.ts +32 -0
  20. package/src/components/editor/propertyPanelColor.tsx +371 -0
  21. package/src/components/editor/propertyPanelFill.tsx +421 -0
  22. package/src/components/editor/propertyPanelFont.tsx +455 -0
  23. package/src/components/editor/propertyPanelHelpers.ts +401 -0
  24. package/src/components/editor/propertyPanelPrimitives.tsx +357 -0
  25. package/src/components/editor/propertyPanelSections.tsx +453 -0
  26. package/src/components/editor/propertyPanelStyleSections.tsx +411 -0
  27. package/src/components/nle/NLELayout.tsx +0 -10
  28. package/src/contexts/DomEditContext.tsx +137 -0
  29. package/src/contexts/FileManagerContext.tsx +110 -0
  30. package/src/contexts/PanelLayoutContext.tsx +68 -0
  31. package/src/contexts/StudioContext.tsx +135 -0
  32. package/src/hooks/useAppHotkeys.ts +326 -0
  33. package/src/hooks/useAskAgentModal.ts +162 -0
  34. package/src/hooks/useCaptionDetection.ts +132 -0
  35. package/src/hooks/useCompositionDimensions.ts +25 -0
  36. package/src/hooks/useConsoleErrorCapture.ts +60 -0
  37. package/src/hooks/useDomEditCommits.ts +437 -0
  38. package/src/hooks/useDomEditSession.ts +342 -0
  39. package/src/hooks/useDomEditTextCommits.ts +330 -0
  40. package/src/hooks/useDomSelection.ts +398 -0
  41. package/src/hooks/useFileManager.ts +431 -0
  42. package/src/hooks/useFrameCapture.ts +77 -0
  43. package/src/hooks/useLintModal.ts +35 -0
  44. package/src/hooks/useManifestPersistence.ts +492 -0
  45. package/src/hooks/usePanelLayout.ts +68 -0
  46. package/src/hooks/usePreviewInteraction.ts +153 -0
  47. package/src/hooks/useRenderClipContent.ts +124 -0
  48. package/src/hooks/useTimelineEditing.ts +472 -0
  49. package/src/player/components/Player.tsx +19 -1
  50. package/src/player/components/Timeline.test.ts +0 -8
  51. package/src/player/components/Timeline.tsx +2 -83
  52. package/src/player/components/TimelineClip.tsx +9 -244
  53. package/src/player/hooks/useTimelinePlayer.ts +140 -103
  54. package/src/utils/domEditHelpers.ts +50 -0
  55. package/src/utils/studioFontHelpers.ts +83 -0
  56. package/src/utils/studioHelpers.ts +214 -0
  57. package/src/utils/studioPreviewHelpers.ts +185 -0
  58. package/dist/assets/hyperframes-player-DjsVzYFP.js +0 -418
  59. package/dist/assets/index-FWg79aJz.css +0 -1
  60. package/dist/assets/index-xdyn_qRZ.js +0 -110
  61. package/src/player/components/TimelineClip.test.ts +0 -92
@@ -1,53 +1,35 @@
1
+ import { memo } from "react";
2
+ import { Eye, Layers, MessageSquare, Move, RotateCcw, X } from "../../icons/SystemIcons";
1
3
  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";
4
+ collectDomEditLayerItems,
5
+ getDomEditLayerKey,
6
+ type DomEditSelection,
7
+ type DomEditLayerItem,
8
+ } from "./domEditing";
9
+ import { readStudioBoxSize, readStudioPathOffset, readStudioRotation } from "./manualEdits";
10
+ import type { ImportedFontAsset } from "./fontAssets";
12
11
  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";
12
+ EMPTY_STYLES,
13
+ formatPxMetricValue,
14
+ LABEL,
15
+ parsePxMetricValue,
16
+ RESPONSIVE_GRID,
17
+ } from "./propertyPanelHelpers";
18
+ import { MetricField, Section } from "./propertyPanelPrimitives";
19
+ import { TextSection, StyleSections } from "./propertyPanelSections";
20
+
21
+ // Re-export helpers that external consumers import from this module
22
+ export {
23
+ buildStrokeStyleUpdates,
24
+ buildStrokeWidthStyleUpdates,
25
+ clampPanelNumber,
26
+ getCssFilterFunctionPx,
27
+ getClipPathInsetPx,
28
+ inferBoxShadowPreset,
29
+ inferClipPathPreset,
30
+ normalizePanelPxValue,
31
+ setCssFilterFunctionPx,
32
+ } from "./propertyPanelHelpers";
51
33
 
52
34
  interface PropertyPanelProps {
53
35
  projectId: string;
@@ -59,6 +41,7 @@ interface PropertyPanelProps {
59
41
  onSetStyle: (prop: string, value: string) => void | Promise<void>;
60
42
  onSetManualOffset: (element: DomEditSelection, next: { x: number; y: number }) => void;
61
43
  onSetManualSize: (element: DomEditSelection, next: { width: number; height: number }) => void;
44
+ onSetManualRotation: (element: DomEditSelection, next: { angle: number }) => void;
62
45
  onSetText: (value: string, fieldKey?: string) => void;
63
46
  onSetTextFieldStyle: (fieldKey: string, property: string, value: string) => void;
64
47
  onAddTextField: (afterFieldKey?: string) => string | Promise<string | null> | null;
@@ -68,2095 +51,73 @@ interface PropertyPanelProps {
68
51
  onImportAssets?: (files: FileList) => Promise<string[]>;
69
52
  fontAssets?: ImportedFontAsset[];
70
53
  onImportFonts?: (files: FileList | File[]) => Promise<ImportedFontAsset[]>;
54
+ activeCompositionPath?: string | null;
55
+ onSelectLayer?: (layer: DomEditLayerItem) => void;
71
56
  }
72
57
 
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({
546
- label,
547
- value,
548
- disabled,
549
- liveCommit,
550
- onCommit,
551
- }: {
552
- label: string;
553
- value: string;
554
- disabled?: boolean;
555
- liveCommit?: boolean;
556
- onCommit: (nextValue: string) => void;
557
- }) {
558
- return (
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
- }
58
+ /* ------------------------------------------------------------------ */
59
+ /* LayerTree */
60
+ /* ------------------------------------------------------------------ */
593
61
 
594
- function TextAreaField({
595
- label,
596
- value,
597
- disabled,
598
- autoFocus,
599
- onCommit,
62
+ function LayerTree({
63
+ element,
64
+ activeCompositionPath,
65
+ onSelectLayer,
600
66
  }: {
601
- label: string;
602
- value: string;
603
- disabled?: boolean;
604
- autoFocus?: boolean;
605
- onCommit: (nextValue: string) => void;
67
+ element: DomEditSelection | null;
68
+ activeCompositionPath: string | null;
69
+ onSelectLayer: (layer: DomEditLayerItem) => void;
606
70
  }) {
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;
71
+ const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
72
+ const layers = collectDomEditLayerItems(element?.element, {
73
+ activeCompositionPath,
74
+ isMasterView,
793
75
  });
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
- }
76
+ if (layers.length <= 1) return null;
1205
77
 
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
- }
78
+ const selectedKey = element ? getDomEditLayerKey(element) : null;
1214
79
 
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
80
  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"]}
1270
- />
1271
- </div>
1272
- );
1273
- }
1274
-
1275
- function ColorField({
1276
- label,
1277
- value,
1278
- disabled,
1279
- onCommit,
1280
- }: {
1281
- label: string;
1282
- value: string;
1283
- disabled?: boolean;
1284
- onCommit: (nextValue: string) => void;
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>
81
+ <Section title="Layers" icon={<Layers size={15} />}>
82
+ <div className="space-y-0.5">
83
+ {layers.map((layer) => {
84
+ const selected = layer.key === selectedKey;
85
+ return (
1404
86
  <button
87
+ key={layer.key}
1405
88
  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
- }}
89
+ onClick={() => onSelectLayer(layer)}
90
+ className={`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors ${
91
+ selected
92
+ ? "bg-studio-accent/14 text-studio-accent"
93
+ : "text-neutral-300 hover:bg-white/[0.04] hover:text-neutral-100"
94
+ }`}
95
+ style={{ paddingLeft: 8 + layer.depth * 12 }}
1427
96
  >
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
-
1512
- return (
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
- >
1523
- <div
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" }}
1526
- />
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 }}
1622
- />
1623
- </div>
1624
- </div>
1625
- );
1626
- }
1627
-
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"
97
+ <span
98
+ className={`flex h-5 w-5 flex-shrink-0 items-center justify-center rounded text-[9px] font-bold uppercase ${
99
+ selected
100
+ ? "bg-studio-accent/18 text-studio-accent"
101
+ : "bg-neutral-800 text-neutral-500"
102
+ }`}
1723
103
  >
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,
104
+ {layer.tagName.slice(0, 2)}
105
+ </span>
106
+ <span className="min-w-0 flex-1 truncate text-xs">{layer.label}</span>
107
+ {layer.childCount > 0 && (
108
+ <span className="text-[9px] tabular-nums text-neutral-500">{layer.childCount}</span>
109
+ )}
110
+ </button>
1784
111
  );
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>
112
+ })}
1862
113
  </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
- }) {
2073
- return (
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
- })}
2096
- </div>
2097
- );
2098
- }
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>
114
+ </Section>
2131
115
  );
2132
116
  }
2133
117
 
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
- }
118
+ /* ------------------------------------------------------------------ */
119
+ /* PropertyPanel */
120
+ /* ------------------------------------------------------------------ */
2160
121
 
2161
122
  export const PropertyPanel = memo(function PropertyPanel({
2162
123
  projectId,
@@ -2168,6 +129,7 @@ export const PropertyPanel = memo(function PropertyPanel({
2168
129
  onSetStyle,
2169
130
  onSetManualOffset,
2170
131
  onSetManualSize,
132
+ onSetManualRotation,
2171
133
  onSetText,
2172
134
  onSetTextFieldStyle,
2173
135
  onAddTextField,
@@ -2177,33 +139,10 @@ export const PropertyPanel = memo(function PropertyPanel({
2177
139
  onImportAssets,
2178
140
  fontAssets = [],
2179
141
  onImportFonts,
142
+ activeCompositionPath = null,
143
+ onSelectLayer,
2180
144
  }: PropertyPanelProps) {
2181
145
  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
146
 
2208
147
  if (!element) {
2209
148
  return (
@@ -2235,25 +174,8 @@ export const PropertyPanel = memo(function PropertyPanel({
2235
174
  );
2236
175
  }
2237
176
 
2238
- const styleEditingDisabled = !element.capabilities.canEditStyles;
2239
177
  const manualOffsetEditingDisabled = !element.capabilities.canApplyManualOffset;
2240
178
  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
179
  const sourceLabel = element.id ? `#${element.id}` : element.selector;
2258
180
  const showEditableSections = element.capabilities.canEditStyles;
2259
181
  const manualOffset = readStudioPathOffset(element.element);
@@ -2295,18 +217,11 @@ export const PropertyPanel = memo(function PropertyPanel({
2295
217
  });
2296
218
  };
2297
219
 
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
- }
220
+ const manualRotation = readStudioRotation(element.element);
221
+ const commitManualRotation = (nextValue: string) => {
222
+ const parsed = Number.parseFloat(nextValue);
223
+ if (!Number.isFinite(parsed)) return;
224
+ onSetManualRotation(element, { angle: parsed });
2310
225
  };
2311
226
 
2312
227
  return (
@@ -2351,217 +266,23 @@ export const PropertyPanel = memo(function PropertyPanel({
2351
266
  </div>
2352
267
 
2353
268
  <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;
2361
-
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>
2373
-
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
- />
269
+ <TextSection
270
+ element={element}
271
+ styles={styles}
272
+ fontAssets={fontAssets}
273
+ onImportFonts={onImportFonts}
274
+ onSetText={onSetText}
275
+ onSetTextFieldStyle={onSetTextFieldStyle}
276
+ onAddTextField={onAddTextField}
277
+ onRemoveTextField={onRemoveTextField}
278
+ />
2551
279
 
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>
280
+ {onSelectLayer && (
281
+ <LayerTree
282
+ element={element}
283
+ activeCompositionPath={activeCompositionPath}
284
+ onSelectLayer={onSelectLayer}
285
+ />
2565
286
  )}
2566
287
 
2567
288
  <Section title="Layout" icon={<Move size={15} />}>
@@ -2570,328 +291,55 @@ export const PropertyPanel = memo(function PropertyPanel({
2570
291
  label="X"
2571
292
  value={formatPxMetricValue(manualOffset.x)}
2572
293
  disabled={manualOffsetEditingDisabled}
294
+ scrub
2573
295
  onCommit={(next) => commitManualOffset("x", next)}
2574
296
  />
2575
297
  <MetricField
2576
298
  label="Y"
2577
299
  value={formatPxMetricValue(manualOffset.y)}
2578
300
  disabled={manualOffsetEditingDisabled}
301
+ scrub
2579
302
  onCommit={(next) => commitManualOffset("y", next)}
2580
303
  />
2581
304
  <MetricField
2582
305
  label="W"
2583
306
  value={formatPxMetricValue(resolvedWidth)}
2584
307
  disabled={manualSizeEditingDisabled}
308
+ scrub
2585
309
  onCommit={(next) => commitManualSize("width", next)}
2586
310
  />
2587
311
  <MetricField
2588
312
  label="H"
2589
313
  value={formatPxMetricValue(resolvedHeight)}
2590
314
  disabled={manualSizeEditingDisabled}
315
+ scrub
2591
316
  onCommit={(next) => commitManualSize("height", next)}
2592
317
  />
318
+ <MetricField
319
+ label="R"
320
+ value={`${manualRotation.angle}°`}
321
+ onCommit={(next) => commitManualRotation(next.replace("°", ""))}
322
+ />
323
+ </div>
324
+ <div className="mt-3">
325
+ <MetricField
326
+ label="Layer"
327
+ value={String(parseInt(styles["z-index"] || "auto", 10) || 0)}
328
+ scrub
329
+ onCommit={(next) => onSetStyle("z-index", next)}
330
+ />
2593
331
  </div>
2594
332
  </Section>
2595
333
 
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
- ]}
2607
- />
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`)}
2636
- />
2637
- </div>
2638
- </Section>
2639
- )}
2640
-
2641
334
  {showEditableSections && (
2642
- <>
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>
2894
- </>
335
+ <StyleSections
336
+ projectId={projectId}
337
+ element={element}
338
+ styles={styles}
339
+ assets={assets}
340
+ onSetStyle={onSetStyle}
341
+ onImportAssets={onImportAssets}
342
+ />
2895
343
  )}
2896
344
  </div>
2897
345
  </div>