@hyperframes/studio 0.5.0-alpha.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/assets/hyperframes-player-CoI5h1xv.js +353 -0
  2. package/dist/assets/index-BKjcNNNd.css +1 -0
  3. package/dist/assets/index-CqiisJmo.js +93 -0
  4. package/dist/index.html +2 -2
  5. package/package.json +4 -4
  6. package/src/App.tsx +208 -1436
  7. package/src/captions/components/CaptionOverlay.tsx +2 -1
  8. package/src/captions/generator.test.ts +19 -0
  9. package/src/captions/generator.ts +9 -2
  10. package/src/captions/hooks/useCaptionSync.ts +6 -1
  11. package/src/captions/keyboard.test.ts +38 -0
  12. package/src/captions/keyboard.ts +8 -0
  13. package/src/captions/parser.test.ts +14 -0
  14. package/src/captions/parser.ts +1 -0
  15. package/src/components/LintModal.tsx +4 -3
  16. package/src/components/editor/PropertyPanel.tsx +206 -2462
  17. package/src/components/nle/NLELayout.tsx +47 -17
  18. package/src/components/nle/NLEPreview.tsx +9 -50
  19. package/src/components/sidebar/AssetsTab.tsx +4 -3
  20. package/src/components/sidebar/CompositionsTab.test.ts +1 -16
  21. package/src/components/sidebar/CompositionsTab.tsx +45 -117
  22. package/src/components/sidebar/LeftSidebar.tsx +55 -34
  23. package/src/components/ui/HyperframesLoader.tsx +104 -0
  24. package/src/components/ui/index.ts +2 -0
  25. package/src/icons/SystemIcons.tsx +2 -0
  26. package/src/player/components/CompositionThumbnail.tsx +10 -42
  27. package/src/player/components/EditModal.tsx +20 -5
  28. package/src/player/components/Player.tsx +129 -28
  29. package/src/player/components/PlayerControls.tsx +117 -49
  30. package/src/player/components/Timeline.test.ts +0 -12
  31. package/src/player/components/Timeline.tsx +25 -52
  32. package/src/player/components/TimelineClip.tsx +9 -21
  33. package/src/player/components/timelineEditing.test.ts +4 -2
  34. package/src/player/components/timelineEditing.ts +3 -1
  35. package/src/player/components/timelineTheme.test.ts +19 -0
  36. package/src/player/components/timelineTheme.ts +8 -4
  37. package/src/player/hooks/useTimelinePlayer.test.ts +219 -1
  38. package/src/player/hooks/useTimelinePlayer.ts +487 -106
  39. package/src/player/lib/time.test.ts +29 -1
  40. package/src/player/lib/time.ts +26 -0
  41. package/src/player/store/playerStore.test.ts +11 -1
  42. package/src/player/store/playerStore.ts +6 -1
  43. package/src/styles/studio.css +112 -0
  44. package/src/utils/frameCapture.test.ts +26 -0
  45. package/src/utils/frameCapture.ts +40 -0
  46. package/src/utils/mediaTypes.ts +1 -1
  47. package/src/utils/projectRouting.test.ts +87 -0
  48. package/src/utils/projectRouting.ts +27 -0
  49. package/src/utils/sourcePatcher.test.ts +1 -128
  50. package/src/utils/sourcePatcher.ts +18 -130
  51. package/src/utils/timelineAssetDrop.test.ts +11 -31
  52. package/src/utils/timelineAssetDrop.ts +2 -22
  53. package/dist/assets/hyperframes-player-vibA20NC.js +0 -198
  54. package/dist/assets/index-0Zt0t13W.css +0 -1
  55. package/dist/assets/index-C9f5eif8.js +0 -105
  56. package/src/components/editor/DomEditOverlay.tsx +0 -442
  57. package/src/components/editor/colorValue.test.ts +0 -82
  58. package/src/components/editor/colorValue.ts +0 -175
  59. package/src/components/editor/domEditing.test.ts +0 -537
  60. package/src/components/editor/domEditing.ts +0 -762
  61. package/src/components/editor/floatingPanel.test.ts +0 -34
  62. package/src/components/editor/floatingPanel.ts +0 -54
  63. package/src/components/editor/fontAssets.ts +0 -32
  64. package/src/components/editor/fontCatalog.ts +0 -126
  65. package/src/components/editor/gradientValue.test.ts +0 -89
  66. package/src/components/editor/gradientValue.ts +0 -445
  67. package/src/player/components/CompositionThumbnail.test.ts +0 -19
  68. package/src/utils/clipboard.test.ts +0 -88
  69. package/src/utils/clipboard.ts +0 -57
@@ -1,445 +0,0 @@
1
- export type GradientKind = "linear" | "radial" | "conic";
2
-
3
- export type RadialSizeKeyword =
4
- | "closest-side"
5
- | "closest-corner"
6
- | "farthest-side"
7
- | "farthest-corner";
8
-
9
- export interface GradientStop {
10
- color: string;
11
- position: number;
12
- }
13
-
14
- export interface GradientModel {
15
- kind: GradientKind;
16
- repeating: boolean;
17
- angle: number;
18
- centerX: number;
19
- centerY: number;
20
- shape: "circle" | "ellipse";
21
- radialSize: RadialSizeKeyword;
22
- stops: GradientStop[];
23
- }
24
-
25
- const RADIAL_SIZE_KEYWORDS: RadialSizeKeyword[] = [
26
- "closest-side",
27
- "closest-corner",
28
- "farthest-side",
29
- "farthest-corner",
30
- ];
31
-
32
- function isWhitespace(char: string | undefined): boolean {
33
- return char === " " || char === "\n" || char === "\r" || char === "\t" || char === "\f";
34
- }
35
-
36
- function isDigit(char: string | undefined): boolean {
37
- return char != null && char >= "0" && char <= "9";
38
- }
39
-
40
- function isSimpleNumber(value: string): boolean {
41
- if (!value) return false;
42
- let index = value[0] === "-" ? 1 : 0;
43
- let digits = 0;
44
-
45
- while (isDigit(value[index])) {
46
- index += 1;
47
- digits += 1;
48
- }
49
-
50
- if (value[index] === ".") {
51
- index += 1;
52
- while (isDigit(value[index])) {
53
- index += 1;
54
- digits += 1;
55
- }
56
- }
57
-
58
- return digits > 0 && index === value.length;
59
- }
60
-
61
- function parseCssNumber(value: string | undefined): number | null {
62
- if (!value) return null;
63
- const trimmed = value.trim();
64
- if (!isSimpleNumber(trimmed)) return null;
65
- const parsed = Number(trimmed);
66
- return Number.isFinite(parsed) ? parsed : null;
67
- }
68
-
69
- function splitCssWhitespace(value: string): string[] {
70
- const tokens: string[] = [];
71
- let current = "";
72
-
73
- for (const char of value) {
74
- if (isWhitespace(char)) {
75
- if (current) {
76
- tokens.push(current);
77
- current = "";
78
- }
79
- continue;
80
- }
81
- current += char;
82
- }
83
-
84
- if (current) tokens.push(current);
85
- return tokens;
86
- }
87
-
88
- function hasCssWord(value: string, word: string): boolean {
89
- return splitCssWhitespace(value.toLowerCase()).includes(word);
90
- }
91
-
92
- function parsePercentToken(value: string | undefined, fallback: number): number {
93
- if (!value?.endsWith("%")) return fallback;
94
- const parsed = parseCssNumber(value.slice(0, -1));
95
- return parsed == null ? fallback : clamp(parsed, 0, 100);
96
- }
97
-
98
- function parseAngleToken(value: string | undefined): number | null {
99
- const trimmed = value?.trim().toLowerCase();
100
- if (!trimmed?.endsWith("deg")) return null;
101
- return parseCssNumber(trimmed.slice(0, -3));
102
- }
103
-
104
- function trailingPercentStart(value: string): number | null {
105
- if (!value.endsWith("%")) return null;
106
- const withoutUnit = value.slice(0, -1).trimEnd();
107
- let start = withoutUnit.length;
108
-
109
- while (start > 0 && (isDigit(withoutUnit[start - 1]) || withoutUnit[start - 1] === ".")) {
110
- start -= 1;
111
- }
112
-
113
- if (start > 0 && withoutUnit[start - 1] === "-") {
114
- start -= 1;
115
- }
116
-
117
- const token = withoutUnit.slice(start);
118
- if (!isSimpleNumber(token)) return null;
119
- if (start === 0 || !isWhitespace(withoutUnit[start - 1])) return null;
120
- return start;
121
- }
122
-
123
- function clamp(value: number, min: number, max: number): number {
124
- return Math.min(max, Math.max(min, value));
125
- }
126
-
127
- function round(value: number): number {
128
- return Math.round(value * 100) / 100;
129
- }
130
-
131
- function parsePercent(value: string | undefined, fallback: number): number {
132
- const parsed = parseCssNumber(value);
133
- return parsed == null ? fallback : clamp(parsed, 0, 100);
134
- }
135
-
136
- function parseColorStop(raw: string): { color: string; position: number | null } {
137
- const trimmed = raw.trim();
138
- const percentStart = trailingPercentStart(trimmed);
139
- if (percentStart == null) return { color: trimmed, position: null };
140
-
141
- const withoutUnit = trimmed.slice(0, -1).trimEnd();
142
- return {
143
- color: withoutUnit.slice(0, percentStart).trim(),
144
- position: parsePercent(withoutUnit.slice(percentStart), 0),
145
- };
146
- }
147
-
148
- function normalizeStops(stops: Array<{ color: string; position: number | null }>): GradientStop[] {
149
- if (stops.length === 0) {
150
- return [
151
- { color: "rgba(60, 230, 172, 0.18)", position: 0 },
152
- { color: "rgba(255, 255, 255, 0.04)", position: 100 },
153
- ];
154
- }
155
-
156
- if (stops.length === 1) {
157
- return [
158
- { color: stops[0].color, position: 0 },
159
- { color: stops[0].color, position: 100 },
160
- ];
161
- }
162
-
163
- const result = stops.map((stop, index) => ({
164
- color: stop.color,
165
- position: stop.position ?? (index / (stops.length - 1)) * 100,
166
- }));
167
-
168
- return result.map((stop) => ({
169
- color: stop.color,
170
- position: round(clamp(stop.position, 0, 100)),
171
- }));
172
- }
173
-
174
- function splitGradientArgs(value: string): string[] {
175
- const parts: string[] = [];
176
- let current = "";
177
- let depth = 0;
178
-
179
- for (const char of value) {
180
- if (char === "(") depth += 1;
181
- if (char === ")") depth = Math.max(0, depth - 1);
182
-
183
- if (char === "," && depth === 0) {
184
- if (current.trim()) parts.push(current.trim());
185
- current = "";
186
- continue;
187
- }
188
-
189
- current += char;
190
- }
191
-
192
- if (current.trim()) parts.push(current.trim());
193
- return parts;
194
- }
195
-
196
- function directionToAngle(value: string): number | null {
197
- const normalized = value.trim().toLowerCase();
198
- const map: Record<string, number> = {
199
- "to top": 0,
200
- "to top right": 45,
201
- "to right top": 45,
202
- "to right": 90,
203
- "to bottom right": 135,
204
- "to right bottom": 135,
205
- "to bottom": 180,
206
- "to bottom left": 225,
207
- "to left bottom": 225,
208
- "to left": 270,
209
- "to top left": 315,
210
- "to left top": 315,
211
- };
212
- return normalized in map ? map[normalized] : null;
213
- }
214
-
215
- function parseLinearArgs(parts: string[]): GradientModel {
216
- const first = parts[0] ?? "";
217
- const angleFromDirection = directionToAngle(first);
218
- const parsedAngle = parseAngleToken(first);
219
- const firstIsAngle = parsedAngle != null;
220
- const angle = parsedAngle ?? angleFromDirection ?? 180;
221
- const stopParts = firstIsAngle || angleFromDirection != null ? parts.slice(1) : parts;
222
-
223
- return {
224
- kind: "linear",
225
- repeating: false,
226
- angle,
227
- centerX: 50,
228
- centerY: 50,
229
- shape: "ellipse",
230
- radialSize: "farthest-corner",
231
- stops: normalizeStops(stopParts.map(parseColorStop)),
232
- };
233
- }
234
-
235
- function parseRadialArgs(parts: string[]): GradientModel {
236
- const first = parts[0] ?? "";
237
- const firstLower = first.toLowerCase();
238
- const hasConfig =
239
- hasCssWord(firstLower, "at") ||
240
- hasCssWord(firstLower, "circle") ||
241
- hasCssWord(firstLower, "ellipse") ||
242
- firstLower.includes("closest-") ||
243
- firstLower.includes("farthest-");
244
- const config = hasConfig ? first : "";
245
- const stopParts = hasConfig ? parts.slice(1) : parts;
246
- const configLower = config.toLowerCase();
247
- const configTokens = splitCssWhitespace(configLower);
248
- const atIndex = configTokens.indexOf("at");
249
-
250
- const shape = hasCssWord(configLower, "circle") ? "circle" : "ellipse";
251
- const radialSize =
252
- RADIAL_SIZE_KEYWORDS.find((keyword) => configTokens.includes(keyword)) ?? "farthest-corner";
253
-
254
- return {
255
- kind: "radial",
256
- repeating: false,
257
- angle: 180,
258
- centerX: parsePercentToken(configTokens[atIndex + 1], 50),
259
- centerY: parsePercentToken(configTokens[atIndex + 2], 50),
260
- shape,
261
- radialSize,
262
- stops: normalizeStops(stopParts.map(parseColorStop)),
263
- };
264
- }
265
-
266
- function parseConicArgs(parts: string[]): GradientModel {
267
- const first = parts[0] ?? "";
268
- const firstLower = first.toLowerCase();
269
- const hasConfig = hasCssWord(firstLower, "from") || hasCssWord(firstLower, "at");
270
- const config = hasConfig ? first : "";
271
- const stopParts = hasConfig ? parts.slice(1) : parts;
272
- const configTokens = splitCssWhitespace(config.toLowerCase());
273
- const fromIndex = configTokens.indexOf("from");
274
- const atIndex = configTokens.indexOf("at");
275
- const angle = parseAngleToken(configTokens[fromIndex + 1]);
276
-
277
- return {
278
- kind: "conic",
279
- repeating: false,
280
- angle: angle ?? 0,
281
- centerX: parsePercentToken(configTokens[atIndex + 1], 50),
282
- centerY: parsePercentToken(configTokens[atIndex + 2], 50),
283
- shape: "ellipse",
284
- radialSize: "farthest-corner",
285
- stops: normalizeStops(stopParts.map(parseColorStop)),
286
- };
287
- }
288
-
289
- export function buildDefaultGradientModel(fallbackColor?: string): GradientModel {
290
- return {
291
- kind: "linear",
292
- repeating: false,
293
- angle: 135,
294
- centerX: 50,
295
- centerY: 50,
296
- shape: "ellipse",
297
- radialSize: "farthest-corner",
298
- stops: normalizeStops([
299
- {
300
- color:
301
- fallbackColor && fallbackColor !== "transparent"
302
- ? fallbackColor
303
- : "rgba(60, 230, 172, 0.18)",
304
- position: 0,
305
- },
306
- { color: "rgba(255, 255, 255, 0.04)", position: 100 },
307
- ]),
308
- };
309
- }
310
-
311
- export function parseGradient(value: string | undefined): GradientModel | null {
312
- if (!value || value === "none") return null;
313
- const trimmed = value.trim();
314
- const openParenIndex = trimmed.indexOf("(");
315
- if (openParenIndex <= 0 || !trimmed.endsWith(")")) return null;
316
-
317
- const functionName = trimmed.slice(0, openParenIndex).toLowerCase();
318
- const kindByFunctionName: Record<string, { kind: GradientKind; repeating: boolean }> = {
319
- "linear-gradient": { kind: "linear", repeating: false },
320
- "radial-gradient": { kind: "radial", repeating: false },
321
- "conic-gradient": { kind: "conic", repeating: false },
322
- "repeating-linear-gradient": { kind: "linear", repeating: true },
323
- "repeating-radial-gradient": { kind: "radial", repeating: true },
324
- "repeating-conic-gradient": { kind: "conic", repeating: true },
325
- };
326
- const parsedFunction = kindByFunctionName[functionName];
327
- if (!parsedFunction) return null;
328
-
329
- const { kind, repeating } = parsedFunction;
330
- const parts = splitGradientArgs(trimmed.slice(openParenIndex + 1, -1));
331
-
332
- const parsed =
333
- kind === "linear"
334
- ? parseLinearArgs(parts)
335
- : kind === "radial"
336
- ? parseRadialArgs(parts)
337
- : parseConicArgs(parts);
338
-
339
- return { ...parsed, repeating };
340
- }
341
-
342
- function formatStop(stop: GradientStop): string {
343
- return `${stop.color} ${round(stop.position)}%`;
344
- }
345
-
346
- export function serializeGradient(model: GradientModel): string {
347
- const fn = `${model.repeating ? "repeating-" : ""}${model.kind}-gradient`;
348
- const stops = model.stops.map(formatStop).join(", ");
349
-
350
- if (model.kind === "linear") {
351
- return `${fn}(${round(model.angle)}deg, ${stops})`;
352
- }
353
-
354
- if (model.kind === "radial") {
355
- return `${fn}(${model.shape} ${model.radialSize} at ${round(model.centerX)}% ${round(
356
- model.centerY,
357
- )}%, ${stops})`;
358
- }
359
-
360
- return `${fn}(from ${round(model.angle)}deg at ${round(model.centerX)}% ${round(
361
- model.centerY,
362
- )}%, ${stops})`;
363
- }
364
-
365
- function blendChannel(start: number, end: number, ratio: number): number {
366
- return Math.round(start + (end - start) * ratio);
367
- }
368
-
369
- function formatHex(channel: number): string {
370
- return channel.toString(16).padStart(2, "0");
371
- }
372
-
373
- export function interpolateGradientStopColor(model: GradientModel, position: number): string {
374
- const clampedPosition = clamp(position, 0, 100);
375
- const sortedStops = [...model.stops].sort((a, b) => a.position - b.position);
376
- const exact = sortedStops.find((stop) => Math.abs(stop.position - clampedPosition) < 0.001);
377
- if (exact) return exact.color;
378
-
379
- const right = sortedStops.find((stop) => stop.position > clampedPosition) ?? sortedStops.at(-1);
380
- const left =
381
- [...sortedStops].reverse().find((stop) => stop.position < clampedPosition) ?? sortedStops[0];
382
- if (!left || !right) return sortedStops[0]?.color ?? "rgba(255, 255, 255, 1)";
383
- if (left === right) return left.color;
384
-
385
- const leftColor = left.color;
386
- const rightColor = right.color;
387
- const leftParsed = leftColor ? parseColorString(leftColor) : null;
388
- const rightParsed = rightColor ? parseColorString(rightColor) : null;
389
- if (!leftParsed || !rightParsed) return left.color;
390
-
391
- const ratio = (clampedPosition - left.position) / Math.max(1, right.position - left.position);
392
- const red = blendChannel(leftParsed.red, rightParsed.red, ratio);
393
- const green = blendChannel(leftParsed.green, rightParsed.green, ratio);
394
- const blue = blendChannel(leftParsed.blue, rightParsed.blue, ratio);
395
- const alpha = round(leftParsed.alpha + (rightParsed.alpha - leftParsed.alpha) * ratio);
396
-
397
- if (alpha >= 1) {
398
- return `#${formatHex(red)}${formatHex(green)}${formatHex(blue)}`.toUpperCase();
399
- }
400
-
401
- return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
402
- }
403
-
404
- export function insertGradientStop(model: GradientModel, position: number): GradientModel {
405
- const clampedPosition = round(clamp(position, 0, 100));
406
- const color = interpolateGradientStopColor(model, clampedPosition);
407
- const nextStops = [...model.stops, { color, position: clampedPosition }].sort(
408
- (a, b) => a.position - b.position,
409
- );
410
- return {
411
- ...model,
412
- stops: nextStops,
413
- };
414
- }
415
-
416
- function parseColorString(
417
- value: string,
418
- ): { red: number; green: number; blue: number; alpha: number } | null {
419
- const trimmed = value.trim().toLowerCase();
420
- if (trimmed === "transparent") {
421
- return { red: 0, green: 0, blue: 0, alpha: 0 };
422
- }
423
-
424
- const hex = trimmed.match(/^#([0-9a-f]{6})$/i);
425
- if (hex) {
426
- return {
427
- red: Number.parseInt(hex[1].slice(0, 2), 16),
428
- green: Number.parseInt(hex[1].slice(2, 4), 16),
429
- blue: Number.parseInt(hex[1].slice(4, 6), 16),
430
- alpha: 1,
431
- };
432
- }
433
-
434
- const rgba = trimmed.match(
435
- /^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/i,
436
- );
437
- if (!rgba) return null;
438
-
439
- return {
440
- red: Number.parseFloat(rgba[1]),
441
- green: Number.parseFloat(rgba[2]),
442
- blue: Number.parseFloat(rgba[3]),
443
- alpha: rgba[4] != null ? Number.parseFloat(rgba[4]) : 1,
444
- };
445
- }
@@ -1,19 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { buildCompositionThumbnailUrl } from "./CompositionThumbnail";
3
-
4
- describe("buildCompositionThumbnailUrl", () => {
5
- it("includes selector and occurrence index for precise element thumbnails", () => {
6
- expect(
7
- buildCompositionThumbnailUrl({
8
- previewUrl: "/api/projects/demo/preview",
9
- seekTime: 1,
10
- duration: 2,
11
- selector: ".card",
12
- selectorIndex: 2,
13
- origin: "http://localhost:3000",
14
- }),
15
- ).toBe(
16
- "http://localhost:3000/api/projects/demo/thumbnail/index.html?t=2.00&v=v2&selector=.card&selectorIndex=2",
17
- );
18
- });
19
- });
@@ -1,88 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
- import { Window } from "happy-dom";
3
- import { copyTextToClipboard } from "./clipboard";
4
-
5
- function installDocument(execCommand: (command: string) => boolean): void {
6
- const window = new Window();
7
- Object.defineProperty(window.document, "execCommand", {
8
- configurable: true,
9
- value: execCommand,
10
- });
11
- vi.stubGlobal("document", window.document);
12
- }
13
-
14
- function installNavigator(
15
- writeText: (text: string) => Promise<void>,
16
- userAgent = "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36",
17
- ): void {
18
- vi.stubGlobal("navigator", {
19
- clipboard: { writeText },
20
- userAgent,
21
- });
22
- }
23
-
24
- describe("copyTextToClipboard", () => {
25
- afterEach(() => {
26
- vi.unstubAllGlobals();
27
- });
28
-
29
- it("uses the synchronous selection copy path first in Safari", async () => {
30
- const execCommand = vi.fn((command: string) => command === "copy");
31
- const writeText = vi.fn((_text: string) => Promise.resolve());
32
-
33
- installDocument(execCommand);
34
- installNavigator(
35
- writeText,
36
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
37
- );
38
-
39
- await expect(copyTextToClipboard("copy me")).resolves.toBe(true);
40
-
41
- expect(execCommand).toHaveBeenCalledWith("copy");
42
- expect(writeText).not.toHaveBeenCalled();
43
- expect(document.querySelector("textarea")).toBeNull();
44
- });
45
-
46
- it("uses navigator.clipboard first outside Safari", async () => {
47
- const execCommand = vi.fn((command: string) => command === "copy");
48
- const writeText = vi.fn((_text: string) => Promise.resolve());
49
-
50
- installDocument(execCommand);
51
- installNavigator(writeText);
52
-
53
- await expect(copyTextToClipboard("copy me")).resolves.toBe(true);
54
-
55
- expect(writeText).toHaveBeenCalledWith("copy me");
56
- expect(execCommand).not.toHaveBeenCalled();
57
- });
58
-
59
- it("falls back to selection copy outside Safari when navigator.clipboard fails", async () => {
60
- const execCommand = vi.fn((command: string) => command === "copy");
61
- const writeText = vi.fn((_text: string) => Promise.reject(new Error("blocked")));
62
-
63
- installDocument(execCommand);
64
- installNavigator(writeText);
65
-
66
- await expect(copyTextToClipboard("copy me")).resolves.toBe(true);
67
-
68
- expect(writeText).toHaveBeenCalledWith("copy me");
69
- expect(execCommand).toHaveBeenCalledWith("copy");
70
- });
71
-
72
- it("reports failure when both copy paths fail", async () => {
73
- const execCommand = vi.fn(() => false);
74
- const writeText = vi.fn((_text: string) => Promise.reject(new Error("blocked")));
75
-
76
- installDocument(execCommand);
77
- installNavigator(
78
- writeText,
79
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
80
- );
81
-
82
- await expect(copyTextToClipboard("copy me")).resolves.toBe(false);
83
-
84
- expect(execCommand).toHaveBeenCalledWith("copy");
85
- expect(writeText).toHaveBeenCalledWith("copy me");
86
- expect(document.querySelector("textarea")).toBeNull();
87
- });
88
- });
@@ -1,57 +0,0 @@
1
- function copyWithSelection(text: string): boolean {
2
- if (typeof document === "undefined" || !document.body || !document.execCommand) {
3
- return false;
4
- }
5
-
6
- const textarea = document.createElement("textarea");
7
- textarea.value = text;
8
- textarea.setAttribute("readonly", "true");
9
- textarea.style.position = "fixed";
10
- textarea.style.top = "0";
11
- textarea.style.left = "0";
12
- textarea.style.width = "1px";
13
- textarea.style.height = "1px";
14
- textarea.style.padding = "0";
15
- textarea.style.border = "0";
16
- textarea.style.opacity = "0";
17
- textarea.style.pointerEvents = "none";
18
-
19
- document.body.appendChild(textarea);
20
- textarea.focus({ preventScroll: true });
21
- textarea.select();
22
- textarea.setSelectionRange(0, text.length);
23
-
24
- try {
25
- return document.execCommand("copy");
26
- } catch {
27
- return false;
28
- } finally {
29
- document.body.removeChild(textarea);
30
- }
31
- }
32
-
33
- function shouldCopyWithSelectionFirst(): boolean {
34
- if (typeof navigator === "undefined") return false;
35
-
36
- const userAgent = navigator.userAgent;
37
- return /Safari/i.test(userAgent) && !/Chrome|Chromium|CriOS|FxiOS|Edg|OPR/i.test(userAgent);
38
- }
39
-
40
- export async function copyTextToClipboard(text: string): Promise<boolean> {
41
- const useSelectionFirst = shouldCopyWithSelectionFirst();
42
- if (useSelectionFirst && copyWithSelection(text)) {
43
- return true;
44
- }
45
-
46
- const clipboard = typeof navigator !== "undefined" ? navigator.clipboard : undefined;
47
- if (clipboard?.writeText) {
48
- try {
49
- await clipboard.writeText(text);
50
- return true;
51
- } catch {
52
- // Fall back below when the browser still allows synchronous copy.
53
- }
54
- }
55
-
56
- return !useSelectionFirst && copyWithSelection(text);
57
- }