react-smart-copy 0.1.0 → 0.2.1
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.
- package/README.md +136 -23
- package/dist/capture.cjs +509 -0
- package/dist/capture.cjs.map +1 -0
- package/dist/capture.d.cts +142 -0
- package/dist/capture.d.ts +142 -0
- package/dist/capture.js +496 -0
- package/dist/capture.js.map +1 -0
- package/dist/core.cjs +579 -23
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +257 -9
- package/dist/core.d.ts +257 -9
- package/dist/core.js +564 -24
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +724 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +328 -12
- package/dist/index.d.ts +328 -12
- package/dist/index.js +706 -43
- package/dist/index.js.map +1 -1
- package/package.json +39 -10
package/dist/index.cjs
CHANGED
|
@@ -17,6 +17,7 @@ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
|
|
|
17
17
|
"permission-denied",
|
|
18
18
|
"not-focused",
|
|
19
19
|
"blob-generation-failed",
|
|
20
|
+
"timeout",
|
|
20
21
|
"unknown"
|
|
21
22
|
]);
|
|
22
23
|
/** Whether retrying the same payload could plausibly succeed. */
|
|
@@ -40,25 +41,35 @@ var CopyFailure = class extends Error {
|
|
|
40
41
|
function isCopyFailure(value) {
|
|
41
42
|
return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
|
|
42
43
|
}
|
|
44
|
+
/** Shorthand for throwing a classified failure. */
|
|
45
|
+
function copyFailure(type, message, cause) {
|
|
46
|
+
return new CopyFailure(createCopyError(type, message, cause));
|
|
47
|
+
}
|
|
43
48
|
function readString(value, key) {
|
|
44
49
|
if (typeof value !== "object" || value === null) return void 0;
|
|
45
50
|
const field = value[key];
|
|
46
51
|
return typeof field === "string" ? field : void 0;
|
|
47
52
|
}
|
|
48
|
-
/**
|
|
49
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Classifies anything thrown by the platform or an adapter into a {@link CopyError}.
|
|
55
|
+
* `operation` only tailors the developer-facing message.
|
|
56
|
+
*/
|
|
57
|
+
function toCopyError(cause, operation = "write") {
|
|
50
58
|
if (isCopyFailure(cause)) return cause.copyError;
|
|
51
59
|
const name = readString(cause, "name");
|
|
52
60
|
const message = readString(cause, "message") ?? "";
|
|
61
|
+
const verb = operation === "read" ? "read" : "write";
|
|
53
62
|
switch (name) {
|
|
54
|
-
case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused",
|
|
63
|
+
case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", `The document was not focused during the clipboard ${verb}.`, cause) : createCopyError("permission-denied", `Clipboard ${verb} permission was denied.`, cause);
|
|
55
64
|
case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
|
|
56
65
|
case "NotSupportedError":
|
|
57
66
|
case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
|
|
58
|
-
|
|
67
|
+
case "AbortError": return createCopyError("aborted", `The clipboard ${verb} was aborted.`, cause);
|
|
68
|
+
case "TimeoutError": return createCopyError("timeout", `The clipboard ${verb} timed out.`, cause);
|
|
69
|
+
default: return createCopyError("unknown", message || `The clipboard ${verb} failed for an unknown reason.`, cause);
|
|
59
70
|
}
|
|
60
71
|
}
|
|
61
|
-
const
|
|
72
|
+
const COPY_DESCRIPTIONS = {
|
|
62
73
|
unsupported: "Copying isn't supported in this browser.",
|
|
63
74
|
"insecure-context": "Copying requires a secure (HTTPS) connection.",
|
|
64
75
|
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
@@ -67,11 +78,34 @@ const DEFAULT_DESCRIPTIONS = {
|
|
|
67
78
|
"unsupported-format": "This content can't be copied in this browser.",
|
|
68
79
|
"blob-generation-failed": "The image couldn't be prepared for copying.",
|
|
69
80
|
"max-retries-exceeded": "Copying failed after several attempts.",
|
|
81
|
+
"no-content": "There is nothing to copy.",
|
|
82
|
+
"too-large": "This content is too large to copy.",
|
|
83
|
+
timeout: "Copying took too long. Try again.",
|
|
84
|
+
aborted: "Copying was cancelled.",
|
|
70
85
|
unknown: "Couldn't copy to the clipboard. Try again."
|
|
71
86
|
};
|
|
72
|
-
|
|
87
|
+
const PASTE_DESCRIPTIONS = {
|
|
88
|
+
unsupported: "Pasting isn't supported in this browser.",
|
|
89
|
+
"insecure-context": "Pasting requires a secure (HTTPS) connection.",
|
|
90
|
+
"permission-denied": "Clipboard access was blocked. Allow it and try again.",
|
|
91
|
+
"not-focused": "The page lost focus while pasting. Try again.",
|
|
92
|
+
"invalid-payload": "The clipboard content couldn't be read.",
|
|
93
|
+
"unsupported-format": "This clipboard content isn't supported here.",
|
|
94
|
+
"blob-generation-failed": "The pasted image couldn't be read.",
|
|
95
|
+
"max-retries-exceeded": "Pasting failed after several attempts.",
|
|
96
|
+
"no-content": "The clipboard doesn't contain anything that can be pasted here.",
|
|
97
|
+
"too-large": "The clipboard content is too large to paste.",
|
|
98
|
+
timeout: "Pasting took too long. Try again.",
|
|
99
|
+
aborted: "Pasting was cancelled.",
|
|
100
|
+
unknown: "Couldn't read the clipboard. Try again."
|
|
101
|
+
};
|
|
102
|
+
/** Default English, user-facing sentence for a copy error. Replace for i18n. */
|
|
73
103
|
function describeCopyError(error) {
|
|
74
|
-
return
|
|
104
|
+
return COPY_DESCRIPTIONS[error.type];
|
|
105
|
+
}
|
|
106
|
+
/** Default English, user-facing sentence for a paste error. Replace for i18n. */
|
|
107
|
+
function describePasteError(error) {
|
|
108
|
+
return PASTE_DESCRIPTIONS[error.type];
|
|
75
109
|
}
|
|
76
110
|
//#endregion
|
|
77
111
|
//#region src/core/payload.ts
|
|
@@ -140,10 +174,82 @@ function serializeJson(payload) {
|
|
|
140
174
|
return text;
|
|
141
175
|
}
|
|
142
176
|
//#endregion
|
|
177
|
+
//#region src/core/mime.ts
|
|
178
|
+
/**
|
|
179
|
+
* MIME helpers shared by paste and capture. Everything that comes from the
|
|
180
|
+
* clipboard is untrusted input, so types are normalised and validated before
|
|
181
|
+
* they are compared, and image types are confirmed from the bytes themselves.
|
|
182
|
+
*/
|
|
183
|
+
/** RFC 6838 token shape, lower-cased. Parameters (`;charset=…`) are stripped first. */
|
|
184
|
+
const MIME_SHAPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
185
|
+
/** SVG is XML that can carry scripts; it is never matched by a wildcard. */
|
|
186
|
+
const SVG_MIME_TYPE = "image/svg+xml";
|
|
187
|
+
/** Lower-cased `type/subtype` without parameters, or `null` if it is not a valid MIME type. */
|
|
188
|
+
function normalizeMimeType(value) {
|
|
189
|
+
const separator = value.indexOf(";");
|
|
190
|
+
const base = (separator === -1 ? value : value.slice(0, separator)).trim().toLowerCase();
|
|
191
|
+
return MIME_SHAPE.test(base) ? base : null;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Does `mimeType` (already normalised) match `pattern` (`type/subtype`, `type/*` or `*\/*`)?
|
|
195
|
+
* Wildcards never match `image/svg+xml`: accepting SVG must be explicit.
|
|
196
|
+
*/
|
|
197
|
+
function matchesMimePattern(mimeType, pattern) {
|
|
198
|
+
if (pattern === mimeType) return true;
|
|
199
|
+
if (mimeType === "image/svg+xml") return false;
|
|
200
|
+
if (pattern === "*/*") return true;
|
|
201
|
+
return pattern.endsWith("/*") && mimeType.startsWith(pattern.slice(0, -1));
|
|
202
|
+
}
|
|
203
|
+
/** Types whose clipboard data is text and is therefore surfaced as a `string`. */
|
|
204
|
+
function isTextualMimeType(mimeType) {
|
|
205
|
+
return mimeType.startsWith("text/") || mimeType === "image/svg+xml" || mimeType === "application/json" || mimeType === "application/xml";
|
|
206
|
+
}
|
|
207
|
+
const SNIFF_BYTES = 16;
|
|
208
|
+
function startsWith(bytes, signature, offset = 0) {
|
|
209
|
+
return signature.every((byte, index) => bytes[offset + index] === byte);
|
|
210
|
+
}
|
|
211
|
+
const ascii = (text) => Array.from(text, (char) => char.charCodeAt(0));
|
|
212
|
+
const PNG = [
|
|
213
|
+
137,
|
|
214
|
+
80,
|
|
215
|
+
78,
|
|
216
|
+
71,
|
|
217
|
+
13,
|
|
218
|
+
10,
|
|
219
|
+
26,
|
|
220
|
+
10
|
|
221
|
+
];
|
|
222
|
+
const JPEG = [
|
|
223
|
+
255,
|
|
224
|
+
216,
|
|
225
|
+
255
|
|
226
|
+
];
|
|
227
|
+
const GIF = ascii("GIF8");
|
|
228
|
+
const RIFF = ascii("RIFF");
|
|
229
|
+
const WEBP = ascii("WEBP");
|
|
230
|
+
const BMP = ascii("BM");
|
|
231
|
+
const FTYP_AVIF = ascii("ftypavif");
|
|
232
|
+
const FTYP_AVIS = ascii("ftypavis");
|
|
233
|
+
/** Identifies a raster image from its magic bytes, ignoring whatever type the Blob claims. */
|
|
234
|
+
function sniffImageBytes(bytes) {
|
|
235
|
+
if (startsWith(bytes, PNG)) return "image/png";
|
|
236
|
+
if (startsWith(bytes, JPEG)) return "image/jpeg";
|
|
237
|
+
if (startsWith(bytes, GIF)) return "image/gif";
|
|
238
|
+
if (startsWith(bytes, RIFF) && startsWith(bytes, WEBP, 8)) return "image/webp";
|
|
239
|
+
if (startsWith(bytes, FTYP_AVIF, 4) || startsWith(bytes, FTYP_AVIS, 4)) return "image/avif";
|
|
240
|
+
if (startsWith(bytes, BMP)) return "image/bmp";
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
/** Reads only the first bytes of a Blob, so sniffing a 20 MB screenshot stays cheap. */
|
|
244
|
+
async function sniffImageType(blob) {
|
|
245
|
+
const head = await blob.slice(0, SNIFF_BYTES).arrayBuffer();
|
|
246
|
+
return sniffImageBytes(new Uint8Array(head));
|
|
247
|
+
}
|
|
248
|
+
//#endregion
|
|
143
249
|
//#region src/core/clipboard-adapter.ts
|
|
144
250
|
const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
|
|
145
251
|
const noop = () => void 0;
|
|
146
|
-
function defaultEnvironment() {
|
|
252
|
+
function defaultEnvironment$1() {
|
|
147
253
|
return typeof window === "undefined" ? void 0 : window;
|
|
148
254
|
}
|
|
149
255
|
function getRichClipboard(env, clipboard) {
|
|
@@ -181,6 +287,7 @@ async function writeImage(rich, source) {
|
|
|
181
287
|
} catch (error) {
|
|
182
288
|
throw await blob.then(noop, (inner) => inner) ?? error;
|
|
183
289
|
}
|
|
290
|
+
await blob;
|
|
184
291
|
}
|
|
185
292
|
async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
186
293
|
if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
@@ -220,16 +327,32 @@ async function writeToClipboard(payload, env, degradeHtmlToText) {
|
|
|
220
327
|
}
|
|
221
328
|
/** The default adapter: async Clipboard API with feature detection and honest errors. */
|
|
222
329
|
function createBrowserClipboardAdapter(options = {}) {
|
|
223
|
-
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
330
|
+
const getEnvironment = options.getEnvironment ?? defaultEnvironment$1;
|
|
224
331
|
const degradeHtmlToText = options.degradeHtmlToText ?? true;
|
|
225
332
|
return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
|
|
226
333
|
}
|
|
227
334
|
//#endregion
|
|
335
|
+
//#region src/core/copy-coordinator.ts
|
|
336
|
+
function createCopyCoordinator() {
|
|
337
|
+
let active = null;
|
|
338
|
+
return {
|
|
339
|
+
activate: (member) => {
|
|
340
|
+
const previous = active;
|
|
341
|
+
active = member;
|
|
342
|
+
if (previous !== null && previous !== member) previous.release();
|
|
343
|
+
},
|
|
344
|
+
deactivate: (member) => {
|
|
345
|
+
if (active === member) active = null;
|
|
346
|
+
},
|
|
347
|
+
getActive: () => active
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
//#endregion
|
|
228
351
|
//#region src/core/copy-machine.ts
|
|
229
352
|
const DEFAULT_RESET_AFTER_MS = 2e3;
|
|
230
353
|
const DEFAULT_MAX_RETRIES = 3;
|
|
231
354
|
const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
232
|
-
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
355
|
+
const IGNORED_IN_FLIGHT$1 = /* @__PURE__ */ Object.freeze({
|
|
233
356
|
status: "ignored",
|
|
234
357
|
reason: "in-flight"
|
|
235
358
|
});
|
|
@@ -246,7 +369,7 @@ function resolveMaxRetries(value) {
|
|
|
246
369
|
if (value === void 0 || !Number.isFinite(value)) return 3;
|
|
247
370
|
return Math.max(0, Math.floor(value));
|
|
248
371
|
}
|
|
249
|
-
function resolveResetDelay(value) {
|
|
372
|
+
function resolveResetDelay$1(value) {
|
|
250
373
|
if (value === false || value === Infinity) return null;
|
|
251
374
|
if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
|
|
252
375
|
return Math.max(0, value);
|
|
@@ -255,7 +378,7 @@ function resolveResetDelay(value) {
|
|
|
255
378
|
function canRetryState(state, maxRetries) {
|
|
256
379
|
return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
|
|
257
380
|
}
|
|
258
|
-
function reportCallbackError(error) {
|
|
381
|
+
function reportCallbackError$1(error) {
|
|
259
382
|
const scope = globalThis;
|
|
260
383
|
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
261
384
|
else setTimeout(() => {
|
|
@@ -263,16 +386,16 @@ function reportCallbackError(error) {
|
|
|
263
386
|
}, 0);
|
|
264
387
|
}
|
|
265
388
|
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
266
|
-
function invoke(fn, ...args) {
|
|
389
|
+
function invoke$1(fn, ...args) {
|
|
267
390
|
if (!fn) return;
|
|
268
391
|
try {
|
|
269
392
|
fn(...args);
|
|
270
393
|
} catch (error) {
|
|
271
|
-
reportCallbackError(error);
|
|
394
|
+
reportCallbackError$1(error);
|
|
272
395
|
}
|
|
273
396
|
}
|
|
274
|
-
let defaultAdapter;
|
|
275
|
-
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserClipboardAdapter());
|
|
397
|
+
let defaultAdapter$1;
|
|
398
|
+
const getDefaultAdapter$1 = () => defaultAdapter$1 ?? (defaultAdapter$1 = createBrowserClipboardAdapter());
|
|
276
399
|
/** Framework-agnostic copy state machine. */
|
|
277
400
|
function createCopyMachine(options = {}) {
|
|
278
401
|
const read = typeof options === "function" ? options : () => options;
|
|
@@ -281,11 +404,27 @@ function createCopyMachine(options = {}) {
|
|
|
281
404
|
let generation = 0;
|
|
282
405
|
let resetTimer;
|
|
283
406
|
const now = () => (read().now ?? Date.now)();
|
|
407
|
+
let joined = null;
|
|
408
|
+
const member = { release: () => {
|
|
409
|
+
if (state.status === "copied") {
|
|
410
|
+
clearResetTimer();
|
|
411
|
+
setState(IDLE_STATE);
|
|
412
|
+
}
|
|
413
|
+
} };
|
|
284
414
|
const setState = (next) => {
|
|
285
415
|
if (next === state) return;
|
|
416
|
+
const previous = state;
|
|
286
417
|
state = next;
|
|
418
|
+
if (previous.status === "copied" && next.status !== "copied" && joined) {
|
|
419
|
+
joined.deactivate(member);
|
|
420
|
+
joined = null;
|
|
421
|
+
}
|
|
287
422
|
for (const listener of Array.from(listeners)) listener();
|
|
288
423
|
};
|
|
424
|
+
const joinCoordinator = () => {
|
|
425
|
+
joined = read().coordinator ?? null;
|
|
426
|
+
joined?.activate(member);
|
|
427
|
+
};
|
|
289
428
|
const clearResetTimer = () => {
|
|
290
429
|
if (resetTimer !== void 0) {
|
|
291
430
|
clearTimeout(resetTimer);
|
|
@@ -294,12 +433,12 @@ function createCopyMachine(options = {}) {
|
|
|
294
433
|
};
|
|
295
434
|
const scheduleReset = (copied) => {
|
|
296
435
|
clearResetTimer();
|
|
297
|
-
const delay = resolveResetDelay(read().resetAfterMs);
|
|
436
|
+
const delay = resolveResetDelay$1(read().resetAfterMs);
|
|
298
437
|
if (delay === null) return;
|
|
299
438
|
const remaining = Math.max(0, delay - (now() - copied.at));
|
|
300
439
|
resetTimer = setTimeout(() => {
|
|
301
440
|
resetTimer = void 0;
|
|
302
|
-
|
|
441
|
+
setState(IDLE_STATE);
|
|
303
442
|
}, remaining);
|
|
304
443
|
};
|
|
305
444
|
const settleError = (error, payload, retryCount) => {
|
|
@@ -309,14 +448,24 @@ function createCopyMachine(options = {}) {
|
|
|
309
448
|
error,
|
|
310
449
|
retryCount
|
|
311
450
|
});
|
|
312
|
-
invoke(read().onError, error, payload);
|
|
451
|
+
invoke$1(read().onError, error, payload);
|
|
313
452
|
};
|
|
314
453
|
const run = (source, retryCount) => {
|
|
315
454
|
clearResetTimer();
|
|
316
455
|
const current = ++generation;
|
|
317
456
|
let payload;
|
|
318
457
|
try {
|
|
319
|
-
|
|
458
|
+
const resolved = typeof source === "function" ? source() : source;
|
|
459
|
+
const resolvedUnknown = resolved;
|
|
460
|
+
if (resolvedUnknown !== null && typeof resolvedUnknown === "object" && typeof resolvedUnknown.then === "function") {
|
|
461
|
+
const error = createCopyError("invalid-payload", "The copy source function must be synchronous. Returning a Promise breaks the user-gesture window required for clipboard writes. Generate your content before calling copy().");
|
|
462
|
+
settleError(error, null, retryCount);
|
|
463
|
+
return Promise.resolve({
|
|
464
|
+
status: "error",
|
|
465
|
+
error
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
payload = normalizePayload(resolved);
|
|
320
469
|
} catch (cause) {
|
|
321
470
|
const error = createCopyError("invalid-payload", "The copy source function threw.", cause);
|
|
322
471
|
settleError(error, null, retryCount);
|
|
@@ -340,7 +489,7 @@ function createCopyMachine(options = {}) {
|
|
|
340
489
|
});
|
|
341
490
|
let pending;
|
|
342
491
|
try {
|
|
343
|
-
pending = (read().adapter ?? getDefaultAdapter()).write(payload);
|
|
492
|
+
pending = (read().adapter ?? getDefaultAdapter$1()).write(payload);
|
|
344
493
|
} catch (cause) {
|
|
345
494
|
pending = Promise.reject(cause);
|
|
346
495
|
}
|
|
@@ -352,8 +501,9 @@ function createCopyMachine(options = {}) {
|
|
|
352
501
|
at: now()
|
|
353
502
|
};
|
|
354
503
|
setState(copied);
|
|
504
|
+
joinCoordinator();
|
|
355
505
|
scheduleReset(copied);
|
|
356
|
-
invoke(read().onCopy, payload);
|
|
506
|
+
invoke$1(read().onCopy, payload);
|
|
357
507
|
}
|
|
358
508
|
return {
|
|
359
509
|
status: "copied",
|
|
@@ -368,7 +518,7 @@ function createCopyMachine(options = {}) {
|
|
|
368
518
|
};
|
|
369
519
|
});
|
|
370
520
|
};
|
|
371
|
-
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
|
|
521
|
+
const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT$1) : run(source, 0);
|
|
372
522
|
const retry = () => {
|
|
373
523
|
if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
|
|
374
524
|
if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
|
|
@@ -410,6 +560,415 @@ function createCopyMachine(options = {}) {
|
|
|
410
560
|
};
|
|
411
561
|
}
|
|
412
562
|
//#endregion
|
|
563
|
+
//#region src/core/paste-reader.ts
|
|
564
|
+
const DEFAULT_PASTE_ACCEPT = /* @__PURE__ */ Object.freeze(["text"]);
|
|
565
|
+
const DEFAULT_PASTE_MAX_BYTES = 33554432;
|
|
566
|
+
const DEFAULT_PASTE_MAX_ITEMS = 32;
|
|
567
|
+
const SHORTHANDS = /* @__PURE__ */ new Map([
|
|
568
|
+
["text", "text/plain"],
|
|
569
|
+
["html", "text/html"],
|
|
570
|
+
["image", "image/*"],
|
|
571
|
+
["any", "*/*"]
|
|
572
|
+
]);
|
|
573
|
+
const TYPE_TOKEN = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/;
|
|
574
|
+
function resolvePattern(entry) {
|
|
575
|
+
if (typeof entry !== "string") return null;
|
|
576
|
+
const shorthand = SHORTHANDS.get(entry);
|
|
577
|
+
if (shorthand !== void 0) return shorthand;
|
|
578
|
+
if (entry === "*/*") return entry;
|
|
579
|
+
if (entry.endsWith("/*")) {
|
|
580
|
+
const type = entry.slice(0, -2).toLowerCase();
|
|
581
|
+
return TYPE_TOKEN.test(type) ? `${type}/*` : null;
|
|
582
|
+
}
|
|
583
|
+
return normalizeMimeType(entry);
|
|
584
|
+
}
|
|
585
|
+
function resolveLimit(value, fallback, name) {
|
|
586
|
+
if (value === void 0) return fallback;
|
|
587
|
+
if (value === Infinity || Number.isInteger(value) && value > 0) return value;
|
|
588
|
+
throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
|
|
589
|
+
}
|
|
590
|
+
/** Validates and normalises paste options. Throws a classified `invalid-payload` failure. */
|
|
591
|
+
function resolvePasteReadOptions(options = {}) {
|
|
592
|
+
const accept = [];
|
|
593
|
+
for (const entry of options.accept ?? DEFAULT_PASTE_ACCEPT) {
|
|
594
|
+
const pattern = resolvePattern(entry);
|
|
595
|
+
if (pattern === null) throw copyFailure("invalid-payload", `Invalid \`accept\` entry: ${JSON.stringify(entry)}.`);
|
|
596
|
+
if (!accept.includes(pattern)) accept.push(pattern);
|
|
597
|
+
}
|
|
598
|
+
if (accept.length === 0) throw copyFailure("invalid-payload", "`accept` must list at least one type.");
|
|
599
|
+
return {
|
|
600
|
+
accept,
|
|
601
|
+
maxBytes: resolveLimit(options.maxBytes, DEFAULT_PASTE_MAX_BYTES, "maxBytes"),
|
|
602
|
+
maxItems: resolveLimit(options.maxItems, 32, "maxItems")
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
/** Whether a normalised MIME type is allowed by the resolved `accept` list. */
|
|
606
|
+
function isAccepted(mimeType, options) {
|
|
607
|
+
return options.accept.some((pattern) => matchesMimePattern(mimeType, pattern));
|
|
608
|
+
}
|
|
609
|
+
function createBudget(options) {
|
|
610
|
+
let bytes = 0;
|
|
611
|
+
let items = 0;
|
|
612
|
+
return { charge: (size) => {
|
|
613
|
+
items += 1;
|
|
614
|
+
bytes += size;
|
|
615
|
+
if (items > options.maxItems) throw copyFailure("too-large", `The paste has more than ${String(options.maxItems)} accepted items.`);
|
|
616
|
+
if (bytes > options.maxBytes) throw copyFailure("too-large", `The paste exceeds the ${String(options.maxBytes)}-byte limit.`);
|
|
617
|
+
} };
|
|
618
|
+
}
|
|
619
|
+
const sizeOf = (data) => typeof data === "string" ? data.length : data.size;
|
|
620
|
+
/** Throws `too-large` when the entries break `maxItems` / `maxBytes`. */
|
|
621
|
+
function enforcePasteLimits(entries, options) {
|
|
622
|
+
const budget = createBudget(options);
|
|
623
|
+
for (const entry of entries) budget.charge(sizeOf(entry.data));
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Synchronously copies the accepted parts of a paste event's `DataTransfer`.
|
|
627
|
+
* It must run during the event: browsers empty the object afterwards.
|
|
628
|
+
*/
|
|
629
|
+
function snapshotDataTransfer(data, options) {
|
|
630
|
+
const entries = [];
|
|
631
|
+
const seen = /* @__PURE__ */ new Set();
|
|
632
|
+
for (const raw of Array.from(data.types)) {
|
|
633
|
+
const type = normalizeMimeType(raw);
|
|
634
|
+
if (type === null || seen.has(type) || !isTextualMimeType(type) || !isAccepted(type, options)) continue;
|
|
635
|
+
seen.add(type);
|
|
636
|
+
const text = data.getData(raw);
|
|
637
|
+
if (text.length > 0) entries.push({
|
|
638
|
+
type,
|
|
639
|
+
data: text,
|
|
640
|
+
file: false
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
for (const file of Array.from(data.files ?? [])) {
|
|
644
|
+
const type = normalizeMimeType(file.type) ?? "application/octet-stream";
|
|
645
|
+
if (isAccepted(type, options)) entries.push({
|
|
646
|
+
type,
|
|
647
|
+
data: file,
|
|
648
|
+
file: true
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
return entries;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Reads the accepted types from `navigator.clipboard.read()` items, enforcing
|
|
655
|
+
* the limits *before* decoding any text so an oversized paste is never buffered twice.
|
|
656
|
+
*/
|
|
657
|
+
async function collectClipboardItems(items, options) {
|
|
658
|
+
const budget = createBudget(options);
|
|
659
|
+
const entries = [];
|
|
660
|
+
const seen = /* @__PURE__ */ new Set();
|
|
661
|
+
for (const item of items) for (const raw of item.types) {
|
|
662
|
+
const type = normalizeMimeType(raw);
|
|
663
|
+
if (type === null || seen.has(type) || !isAccepted(type, options)) continue;
|
|
664
|
+
seen.add(type);
|
|
665
|
+
let blob;
|
|
666
|
+
try {
|
|
667
|
+
blob = await item.getType(raw);
|
|
668
|
+
} catch {
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
if (blob.size === 0) continue;
|
|
672
|
+
budget.charge(blob.size);
|
|
673
|
+
entries.push({
|
|
674
|
+
type,
|
|
675
|
+
data: isTextualMimeType(type) ? await blob.text() : blob,
|
|
676
|
+
file: false
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
return entries;
|
|
680
|
+
}
|
|
681
|
+
function retype(entry, data, type) {
|
|
682
|
+
if (entry.file) {
|
|
683
|
+
const file = data;
|
|
684
|
+
return new File([file], file.name, {
|
|
685
|
+
type,
|
|
686
|
+
lastModified: file.lastModified
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
return data.slice(0, data.size, type);
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Verifies image bytes, then builds the result. Blobs that claim to be images
|
|
693
|
+
* but aren't (or whose real format is not accepted) are dropped. Throws
|
|
694
|
+
* `no-content` when nothing survives.
|
|
695
|
+
*/
|
|
696
|
+
async function finalizePaste(entries, source, options) {
|
|
697
|
+
const items = [];
|
|
698
|
+
const images = [];
|
|
699
|
+
const files = [];
|
|
700
|
+
let text = null;
|
|
701
|
+
let html = null;
|
|
702
|
+
for (const entry of entries) {
|
|
703
|
+
let { type, data } = entry;
|
|
704
|
+
if (typeof data === "string") {
|
|
705
|
+
if (type === "text/plain") text = data;
|
|
706
|
+
else if (type === "text/html") html = data;
|
|
707
|
+
} else if (type.startsWith("image/")) {
|
|
708
|
+
const actual = await sniffImageType(data);
|
|
709
|
+
if (actual === null || !isAccepted(actual, options)) continue;
|
|
710
|
+
if (actual !== type) {
|
|
711
|
+
data = retype(entry, data, actual);
|
|
712
|
+
type = actual;
|
|
713
|
+
}
|
|
714
|
+
images.push(data);
|
|
715
|
+
}
|
|
716
|
+
if (entry.file) files.push(data);
|
|
717
|
+
items.push({
|
|
718
|
+
type,
|
|
719
|
+
data
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
if (items.length === 0) throw copyFailure("no-content", "The clipboard holds nothing that matches `accept`.");
|
|
723
|
+
return {
|
|
724
|
+
source,
|
|
725
|
+
items,
|
|
726
|
+
text,
|
|
727
|
+
html,
|
|
728
|
+
images,
|
|
729
|
+
files
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
//#endregion
|
|
733
|
+
//#region src/core/paste-adapter.ts
|
|
734
|
+
function defaultEnvironment() {
|
|
735
|
+
return typeof window === "undefined" ? void 0 : window;
|
|
736
|
+
}
|
|
737
|
+
const canRead = (clipboard) => typeof clipboard.read === "function";
|
|
738
|
+
const canReadText = (clipboard) => typeof clipboard.readText === "function";
|
|
739
|
+
async function readPlainText(clipboard, options) {
|
|
740
|
+
let text;
|
|
741
|
+
try {
|
|
742
|
+
text = await clipboard.readText();
|
|
743
|
+
} catch (cause) {
|
|
744
|
+
throw new CopyFailure(toCopyError(cause, "read"));
|
|
745
|
+
}
|
|
746
|
+
const entries = text.length > 0 ? [{
|
|
747
|
+
type: "text/plain",
|
|
748
|
+
data: text,
|
|
749
|
+
file: false
|
|
750
|
+
}] : [];
|
|
751
|
+
enforcePasteLimits(entries, options);
|
|
752
|
+
return finalizePaste(entries, "clipboard", options);
|
|
753
|
+
}
|
|
754
|
+
async function readRich(clipboard, options) {
|
|
755
|
+
let items;
|
|
756
|
+
try {
|
|
757
|
+
items = await clipboard.read();
|
|
758
|
+
} catch (cause) {
|
|
759
|
+
throw new CopyFailure(toCopyError(cause, "read"));
|
|
760
|
+
}
|
|
761
|
+
return finalizePaste(await collectClipboardItems(items, options), "clipboard", options);
|
|
762
|
+
}
|
|
763
|
+
function readFromClipboard(env, options) {
|
|
764
|
+
if (!env) throw copyFailure("unsupported", "No browser environment: the clipboard only exists in the browser.");
|
|
765
|
+
if (env.isSecureContext === false) throw copyFailure("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
|
|
766
|
+
const clipboard = env.navigator?.clipboard;
|
|
767
|
+
if (!clipboard) throw copyFailure("unsupported", "navigator.clipboard is not available in this browser.");
|
|
768
|
+
const plainOnly = options.accept.every((pattern) => pattern === "text/plain");
|
|
769
|
+
const acceptsPlain = options.accept.some((pattern) => matchesMimePattern("text/plain", pattern));
|
|
770
|
+
if (canRead(clipboard) && !(plainOnly && canReadText(clipboard))) return readRich(clipboard, options);
|
|
771
|
+
if (canReadText(clipboard) && acceptsPlain) return readPlainText(clipboard, options);
|
|
772
|
+
throw canReadText(clipboard) ? copyFailure("unsupported-format", "Reading non-text clipboard content requires navigator.clipboard.read().") : copyFailure("unsupported", "This browser cannot read the clipboard.");
|
|
773
|
+
}
|
|
774
|
+
/** The default paste adapter: async Clipboard API with feature detection and honest errors. */
|
|
775
|
+
function createBrowserPasteAdapter(options = {}) {
|
|
776
|
+
const getEnvironment = options.getEnvironment ?? defaultEnvironment;
|
|
777
|
+
return { read: (resolved) => {
|
|
778
|
+
try {
|
|
779
|
+
return readFromClipboard(getEnvironment(), resolved);
|
|
780
|
+
} catch (cause) {
|
|
781
|
+
return Promise.reject(cause);
|
|
782
|
+
}
|
|
783
|
+
} };
|
|
784
|
+
}
|
|
785
|
+
//#endregion
|
|
786
|
+
//#region src/core/paste-machine.ts
|
|
787
|
+
const PASTE_IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
|
|
788
|
+
const PASTE_READING_STATE = /* @__PURE__ */ Object.freeze({ status: "reading" });
|
|
789
|
+
const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
|
|
790
|
+
status: "ignored",
|
|
791
|
+
reason: "in-flight"
|
|
792
|
+
});
|
|
793
|
+
const IGNORED_NO_CONTENT = /* @__PURE__ */ Object.freeze({
|
|
794
|
+
status: "ignored",
|
|
795
|
+
reason: "no-accepted-content"
|
|
796
|
+
});
|
|
797
|
+
function resolveResetDelay(value) {
|
|
798
|
+
if (value === void 0 || value === false || value === Infinity || Number.isNaN(value)) return null;
|
|
799
|
+
return Math.max(0, value);
|
|
800
|
+
}
|
|
801
|
+
function reportCallbackError(error) {
|
|
802
|
+
const scope = globalThis;
|
|
803
|
+
if (typeof scope.reportError === "function") scope.reportError(error);
|
|
804
|
+
else setTimeout(() => {
|
|
805
|
+
throw error;
|
|
806
|
+
}, 0);
|
|
807
|
+
}
|
|
808
|
+
/** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
|
|
809
|
+
function invoke(fn, ...args) {
|
|
810
|
+
if (!fn) return;
|
|
811
|
+
try {
|
|
812
|
+
fn(...args);
|
|
813
|
+
} catch (error) {
|
|
814
|
+
reportCallbackError(error);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
let defaultAdapter;
|
|
818
|
+
const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserPasteAdapter());
|
|
819
|
+
/** Framework-agnostic paste state machine. */
|
|
820
|
+
function createPasteMachine(options = {}) {
|
|
821
|
+
const read = typeof options === "function" ? options : () => options;
|
|
822
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
823
|
+
let state = PASTE_IDLE_STATE;
|
|
824
|
+
let generation = 0;
|
|
825
|
+
let resetTimer;
|
|
826
|
+
const now = () => (read().now ?? Date.now)();
|
|
827
|
+
const setState = (next) => {
|
|
828
|
+
if (next === state) return;
|
|
829
|
+
state = next;
|
|
830
|
+
for (const listener of Array.from(listeners)) listener();
|
|
831
|
+
};
|
|
832
|
+
const clearResetTimer = () => {
|
|
833
|
+
if (resetTimer !== void 0) {
|
|
834
|
+
clearTimeout(resetTimer);
|
|
835
|
+
resetTimer = void 0;
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
const scheduleReset = (readState) => {
|
|
839
|
+
clearResetTimer();
|
|
840
|
+
const delay = resolveResetDelay(read().resetAfterMs);
|
|
841
|
+
if (delay === null) return;
|
|
842
|
+
const remaining = Math.max(0, delay - (now() - readState.at));
|
|
843
|
+
resetTimer = setTimeout(() => {
|
|
844
|
+
resetTimer = void 0;
|
|
845
|
+
setState(PASTE_IDLE_STATE);
|
|
846
|
+
}, remaining);
|
|
847
|
+
};
|
|
848
|
+
/** Runs one read. `produce` is invoked synchronously so the user gesture is preserved. */
|
|
849
|
+
const run = (produce) => {
|
|
850
|
+
clearResetTimer();
|
|
851
|
+
const current = ++generation;
|
|
852
|
+
setState(PASTE_READING_STATE);
|
|
853
|
+
let pending;
|
|
854
|
+
try {
|
|
855
|
+
pending = produce();
|
|
856
|
+
} catch (cause) {
|
|
857
|
+
pending = Promise.reject(cause);
|
|
858
|
+
}
|
|
859
|
+
return pending.then((result) => {
|
|
860
|
+
if (current === generation) {
|
|
861
|
+
const readState = {
|
|
862
|
+
status: "read",
|
|
863
|
+
result,
|
|
864
|
+
at: now()
|
|
865
|
+
};
|
|
866
|
+
setState(readState);
|
|
867
|
+
scheduleReset(readState);
|
|
868
|
+
invoke(read().onPaste, result);
|
|
869
|
+
}
|
|
870
|
+
return {
|
|
871
|
+
status: "read",
|
|
872
|
+
result
|
|
873
|
+
};
|
|
874
|
+
}, (cause) => {
|
|
875
|
+
const error = toCopyError(cause, "read");
|
|
876
|
+
if (current === generation) {
|
|
877
|
+
setState({
|
|
878
|
+
status: "error",
|
|
879
|
+
error
|
|
880
|
+
});
|
|
881
|
+
invoke(read().onError, error);
|
|
882
|
+
}
|
|
883
|
+
return {
|
|
884
|
+
status: "error",
|
|
885
|
+
error
|
|
886
|
+
};
|
|
887
|
+
});
|
|
888
|
+
};
|
|
889
|
+
const paste = () => {
|
|
890
|
+
if (state.status === "reading") return Promise.resolve(IGNORED_IN_FLIGHT);
|
|
891
|
+
return run(() => {
|
|
892
|
+
const resolved = resolvePasteReadOptions(read());
|
|
893
|
+
return (read().adapter ?? getDefaultAdapter()).read(resolved);
|
|
894
|
+
});
|
|
895
|
+
};
|
|
896
|
+
const pasteEvent = (event) => {
|
|
897
|
+
const data = event.clipboardData;
|
|
898
|
+
if (!data) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
899
|
+
const current = read();
|
|
900
|
+
let resolved;
|
|
901
|
+
try {
|
|
902
|
+
resolved = resolvePasteReadOptions(current);
|
|
903
|
+
} catch (cause) {
|
|
904
|
+
const error = toCopyError(cause, "read");
|
|
905
|
+
++generation;
|
|
906
|
+
clearResetTimer();
|
|
907
|
+
setState({
|
|
908
|
+
status: "error",
|
|
909
|
+
error
|
|
910
|
+
});
|
|
911
|
+
invoke(current.onError, error);
|
|
912
|
+
return Promise.resolve({
|
|
913
|
+
status: "error",
|
|
914
|
+
error
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
const entries = snapshotDataTransfer(data, resolved);
|
|
918
|
+
if (entries.length === 0) return Promise.resolve(IGNORED_NO_CONTENT);
|
|
919
|
+
if (current.preventDefault !== false) event.preventDefault();
|
|
920
|
+
return run(() => {
|
|
921
|
+
enforcePasteLimits(entries, resolved);
|
|
922
|
+
return finalizePaste(entries, "event", resolved);
|
|
923
|
+
});
|
|
924
|
+
};
|
|
925
|
+
const reset = () => {
|
|
926
|
+
++generation;
|
|
927
|
+
clearResetTimer();
|
|
928
|
+
setState(PASTE_IDLE_STATE);
|
|
929
|
+
};
|
|
930
|
+
const connect = () => {
|
|
931
|
+
if (state.status === "read") scheduleReset(state);
|
|
932
|
+
return () => {
|
|
933
|
+
++generation;
|
|
934
|
+
clearResetTimer();
|
|
935
|
+
if (state.status === "reading") setState(PASTE_IDLE_STATE);
|
|
936
|
+
};
|
|
937
|
+
};
|
|
938
|
+
return {
|
|
939
|
+
getSnapshot: () => state,
|
|
940
|
+
subscribe: (listener) => {
|
|
941
|
+
listeners.add(listener);
|
|
942
|
+
return () => {
|
|
943
|
+
listeners.delete(listener);
|
|
944
|
+
};
|
|
945
|
+
},
|
|
946
|
+
paste,
|
|
947
|
+
pasteEvent,
|
|
948
|
+
reset,
|
|
949
|
+
connect
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
//#endregion
|
|
953
|
+
//#region src/react/CopyGroup.tsx
|
|
954
|
+
const CopyGroupContext = /* @__PURE__ */ (0, react.createContext)(null);
|
|
955
|
+
/**
|
|
956
|
+
* Every `useCopy` / `<CopyField.Root>` inside behaves like one clipboard:
|
|
957
|
+
* a new successful copy returns the previously "Copied" one to idle.
|
|
958
|
+
* Opt a single field out with `copyOptions={{ coordinator: null }}`. Groups nest; the nearest wins.
|
|
959
|
+
*/
|
|
960
|
+
function CopyGroup({ children, coordinator }) {
|
|
961
|
+
const [owned] = (0, react.useState)(createCopyCoordinator);
|
|
962
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopyGroupContext.Provider, {
|
|
963
|
+
value: coordinator ?? owned,
|
|
964
|
+
children
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
/** The nearest `<CopyGroup>`'s coordinator, or `null` outside any group. */
|
|
968
|
+
function useCopyGroup() {
|
|
969
|
+
return (0, react.useContext)(CopyGroupContext);
|
|
970
|
+
}
|
|
971
|
+
//#endregion
|
|
413
972
|
//#region src/react/utils.ts
|
|
414
973
|
/** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */
|
|
415
974
|
const useIsomorphicLayoutEffect = typeof window === "undefined" ? react.useEffect : react.useLayoutEffect;
|
|
@@ -428,19 +987,27 @@ function composeEventHandlers(theirs, ours) {
|
|
|
428
987
|
}
|
|
429
988
|
//#endregion
|
|
430
989
|
//#region src/react/useCopy.ts
|
|
431
|
-
const getServerSnapshot$
|
|
990
|
+
const getServerSnapshot$2 = () => IDLE_STATE;
|
|
991
|
+
/** An explicit `coordinator` (including `null`) wins over the surrounding `<CopyGroup>`. */
|
|
992
|
+
function withGroup(options, group) {
|
|
993
|
+
return options.coordinator !== void 0 || group === null ? options : {
|
|
994
|
+
...options,
|
|
995
|
+
coordinator: group
|
|
996
|
+
};
|
|
997
|
+
}
|
|
432
998
|
/**
|
|
433
999
|
* Copy state machine bound to a component. Options may change on every render
|
|
434
1000
|
* (inline callbacks are fine); the latest ones are always used.
|
|
435
1001
|
*/
|
|
436
1002
|
function useCopy(options = {}) {
|
|
437
|
-
const
|
|
1003
|
+
const effective = withGroup(options, useCopyGroup());
|
|
1004
|
+
const optionsRef = (0, react.useRef)(effective);
|
|
438
1005
|
useIsomorphicLayoutEffect(() => {
|
|
439
|
-
optionsRef.current =
|
|
1006
|
+
optionsRef.current = effective;
|
|
440
1007
|
});
|
|
441
1008
|
const [machine] = (0, react.useState)(() => createCopyMachine(() => optionsRef.current));
|
|
442
1009
|
(0, react.useEffect)(() => machine.connect(), [machine]);
|
|
443
|
-
const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot$
|
|
1010
|
+
const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot$2);
|
|
444
1011
|
const canRetry = canRetryState(state, options.maxRetries);
|
|
445
1012
|
return (0, react.useMemo)(() => ({
|
|
446
1013
|
state,
|
|
@@ -458,22 +1025,29 @@ function useCopy(options = {}) {
|
|
|
458
1025
|
}
|
|
459
1026
|
//#endregion
|
|
460
1027
|
//#region src/react/useMediaQuery.ts
|
|
461
|
-
const getServerSnapshot = () => false;
|
|
462
|
-
function getMediaQueryList(query) {
|
|
463
|
-
return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(query) : null;
|
|
464
|
-
}
|
|
1028
|
+
const getServerSnapshot$1 = () => false;
|
|
465
1029
|
/** SSR-safe media query subscription. Server and hydration render `false`. */
|
|
466
1030
|
function useMediaQuery(query) {
|
|
1031
|
+
const listRef = (0, react.useRef)(null);
|
|
1032
|
+
const queryRef = (0, react.useRef)("");
|
|
1033
|
+
const getList = (0, react.useCallback)(() => {
|
|
1034
|
+
if (typeof window === "undefined" || typeof window.matchMedia !== "function") return null;
|
|
1035
|
+
if (listRef.current === null || queryRef.current !== query) {
|
|
1036
|
+
listRef.current = window.matchMedia(query);
|
|
1037
|
+
queryRef.current = query;
|
|
1038
|
+
}
|
|
1039
|
+
return listRef.current;
|
|
1040
|
+
}, [query]);
|
|
467
1041
|
const subscribe = (0, react.useCallback)((onChange) => {
|
|
468
|
-
const list =
|
|
1042
|
+
const list = getList();
|
|
469
1043
|
if (!list) return () => void 0;
|
|
470
1044
|
list.addEventListener("change", onChange);
|
|
471
1045
|
return () => {
|
|
472
1046
|
list.removeEventListener("change", onChange);
|
|
473
1047
|
};
|
|
474
|
-
}, [
|
|
475
|
-
const getSnapshot = (0, react.useCallback)(() =>
|
|
476
|
-
return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getServerSnapshot);
|
|
1048
|
+
}, [getList]);
|
|
1049
|
+
const getSnapshot = (0, react.useCallback)(() => getList()?.matches ?? false, [getList]);
|
|
1050
|
+
return (0, react.useSyncExternalStore)(subscribe, getSnapshot, getServerSnapshot$1);
|
|
477
1051
|
}
|
|
478
1052
|
//#endregion
|
|
479
1053
|
//#region src/react/useRevealOnInteraction.ts
|
|
@@ -558,7 +1132,9 @@ function useDisplayStatus(status, options = {}) {
|
|
|
558
1132
|
const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? 150);
|
|
559
1133
|
const minPendingMs = Math.max(0, options.minPendingMs ?? 400);
|
|
560
1134
|
const [settled, setSettled] = (0, react.useState)(status === "copying" ? "idle" : status);
|
|
561
|
-
|
|
1135
|
+
useIsomorphicLayoutEffect(() => {
|
|
1136
|
+
if (status !== "copying") setSettled(status);
|
|
1137
|
+
}, [status]);
|
|
562
1138
|
const [pendingShownAt, setPendingShownAt] = (0, react.useState)(null);
|
|
563
1139
|
(0, react.useEffect)(() => {
|
|
564
1140
|
if (status !== "copying") return void 0;
|
|
@@ -603,18 +1179,43 @@ const visuallyHiddenStyle = {
|
|
|
603
1179
|
/**
|
|
604
1180
|
* Always-mounted announcer. Screen readers ignore regions that are inserted
|
|
605
1181
|
* together with their content, so this must render before the first message.
|
|
1182
|
+
*
|
|
1183
|
+
* **Mount safety**: the live region is intentionally empty on mount. We write
|
|
1184
|
+
* the message into the DOM imperatively (via a ref) only after the element has
|
|
1185
|
+
* been live for at least one browser paint. This prevents SSR hydration and
|
|
1186
|
+
* strict-mode double-mount from producing a spurious announcement on some
|
|
1187
|
+
* screen readers (JAWS / NVDA observe the initial DOM during hydration and
|
|
1188
|
+
* re-read regions that already have text content).
|
|
1189
|
+
*
|
|
1190
|
+
* **WCAG 4.1.3 / ARIA spec**: we use `role="status"` with explicit `aria-live`
|
|
1191
|
+
* rather than `role="alert"`. `role="alert"` interrupts any sentence being
|
|
1192
|
+
* spoken even in polite mode, which is inappropriate for copy feedback.
|
|
1193
|
+
* `role="status"` + `aria-live` is correct for both politeness levels.
|
|
606
1194
|
*/
|
|
607
1195
|
function LiveRegion({ message, politeness = "polite", visuallyHidden = true, style, ...rest }) {
|
|
1196
|
+
const spanRef = (0, react.useRef)(null);
|
|
1197
|
+
const mountedRef = (0, react.useRef)(false);
|
|
1198
|
+
(0, react.useEffect)(() => {
|
|
1199
|
+
mountedRef.current = true;
|
|
1200
|
+
}, []);
|
|
1201
|
+
(0, react.useEffect)(() => {
|
|
1202
|
+
const span = spanRef.current;
|
|
1203
|
+
/* c8 ignore next -- spanRef.current is always set by mount; guard for unmounted edge case */
|
|
1204
|
+
if (!span) return;
|
|
1205
|
+
/* c8 ignore next -- jsdom effects run synchronously so mountedRef.current is always true here; this guard only fires in real browsers during the initial paint */
|
|
1206
|
+
if (!mountedRef.current) return;
|
|
1207
|
+
span.textContent = message;
|
|
1208
|
+
}, [message]);
|
|
608
1209
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
609
1210
|
...rest,
|
|
610
|
-
|
|
1211
|
+
ref: spanRef,
|
|
1212
|
+
role: "status",
|
|
611
1213
|
"aria-live": politeness,
|
|
612
1214
|
"aria-atomic": "true",
|
|
613
1215
|
style: visuallyHidden ? {
|
|
614
1216
|
...visuallyHiddenStyle,
|
|
615
1217
|
...style
|
|
616
|
-
} : style
|
|
617
|
-
children: message
|
|
1218
|
+
} : style
|
|
618
1219
|
});
|
|
619
1220
|
}
|
|
620
1221
|
//#endregion
|
|
@@ -631,10 +1232,23 @@ function useCopyField() {
|
|
|
631
1232
|
if (!context) throw new Error("useCopyField() must be used inside <CopyField.Root>.");
|
|
632
1233
|
return context;
|
|
633
1234
|
}
|
|
1235
|
+
/** Maps non-text payload kinds to a human-readable description for screen readers. */
|
|
1236
|
+
const KIND_LABELS = /* @__PURE__ */ Object.freeze({
|
|
1237
|
+
html: "Rich text",
|
|
1238
|
+
image: "Image",
|
|
1239
|
+
json: "JSON data",
|
|
1240
|
+
multi: "Mixed content"
|
|
1241
|
+
});
|
|
1242
|
+
/**
|
|
1243
|
+
* Returns the value's text representation when it is plain text, or a
|
|
1244
|
+
* descriptive fallback for non-text payloads so screen-reader users understand
|
|
1245
|
+
* what will be copied (A1: `CopyField.Value` must never be silent).
|
|
1246
|
+
*/
|
|
634
1247
|
function getDisplayValue(value) {
|
|
635
1248
|
if (typeof value === "string") return value;
|
|
636
|
-
if (typeof value === "
|
|
637
|
-
return
|
|
1249
|
+
if (typeof value === "function") return null;
|
|
1250
|
+
if (value.kind === "text") return value.value;
|
|
1251
|
+
return KIND_LABELS[value.kind] ?? null;
|
|
638
1252
|
}
|
|
639
1253
|
const Root = /* @__PURE__ */ (0, react.forwardRef)(function CopyFieldRoot({ value, label, copyOptions, messages: messageOverrides, alwaysVisible = false, announce = true, pendingDelayMs, minPendingMs, children, onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur, ...rest }, forwardedRef) {
|
|
640
1254
|
const copyState = useCopy(copyOptions);
|
|
@@ -773,11 +1387,13 @@ const CopyField = {
|
|
|
773
1387
|
revealed: field.revealed,
|
|
774
1388
|
canRetry: field.canRetry
|
|
775
1389
|
};
|
|
1390
|
+
const computedAriaLabel = ariaLabel ?? field.messages.triggerLabel(field.label);
|
|
1391
|
+
const safeAriaLabel = computedAriaLabel.length > 0 ? computedAriaLabel : `Copy ${field.label}`;
|
|
776
1392
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
|
777
1393
|
...rest,
|
|
778
1394
|
ref,
|
|
779
1395
|
type: "button",
|
|
780
|
-
"aria-label":
|
|
1396
|
+
"aria-label": safeAriaLabel,
|
|
781
1397
|
"data-state": field.status,
|
|
782
1398
|
"data-display-state": field.displayStatus,
|
|
783
1399
|
"data-revealed": field.revealed ? "" : void 0,
|
|
@@ -789,31 +1405,97 @@ const CopyField = {
|
|
|
789
1405
|
})
|
|
790
1406
|
};
|
|
791
1407
|
//#endregion
|
|
1408
|
+
//#region src/react/usePaste.ts
|
|
1409
|
+
const getServerSnapshot = () => PASTE_IDLE_STATE;
|
|
1410
|
+
/**
|
|
1411
|
+
* Paste state machine bound to a component. Supports a "Paste" button
|
|
1412
|
+
* (`paste()`, may prompt for permission) and keyboard paste (`targetProps`
|
|
1413
|
+
* or `listenOnDocument`, no prompt). Options may change on every render.
|
|
1414
|
+
*
|
|
1415
|
+
* Everything in the result is untrusted user input.
|
|
1416
|
+
*/
|
|
1417
|
+
function usePaste(options = {}) {
|
|
1418
|
+
const optionsRef = (0, react.useRef)(options);
|
|
1419
|
+
useIsomorphicLayoutEffect(() => {
|
|
1420
|
+
optionsRef.current = options;
|
|
1421
|
+
});
|
|
1422
|
+
const [machine] = (0, react.useState)(() => createPasteMachine(() => optionsRef.current));
|
|
1423
|
+
(0, react.useEffect)(() => machine.connect(), [machine]);
|
|
1424
|
+
const listenOnDocument = options.listenOnDocument === true;
|
|
1425
|
+
(0, react.useEffect)(() => {
|
|
1426
|
+
if (!listenOnDocument) return void 0;
|
|
1427
|
+
const onPaste = (event) => {
|
|
1428
|
+
if (!event.defaultPrevented) machine.pasteEvent(event);
|
|
1429
|
+
};
|
|
1430
|
+
document.addEventListener("paste", onPaste);
|
|
1431
|
+
return () => {
|
|
1432
|
+
document.removeEventListener("paste", onPaste);
|
|
1433
|
+
};
|
|
1434
|
+
}, [listenOnDocument, machine]);
|
|
1435
|
+
const state = (0, react.useSyncExternalStore)(machine.subscribe, machine.getSnapshot, getServerSnapshot);
|
|
1436
|
+
const targetProps = (0, react.useMemo)(() => ({ onPaste: (event) => {
|
|
1437
|
+
machine.pasteEvent(event);
|
|
1438
|
+
} }), [machine]);
|
|
1439
|
+
return (0, react.useMemo)(() => ({
|
|
1440
|
+
state,
|
|
1441
|
+
status: state.status,
|
|
1442
|
+
result: state.status === "read" ? state.result : null,
|
|
1443
|
+
error: state.status === "error" ? state.error : null,
|
|
1444
|
+
paste: machine.paste,
|
|
1445
|
+
pasteEvent: machine.pasteEvent,
|
|
1446
|
+
reset: machine.reset,
|
|
1447
|
+
targetProps
|
|
1448
|
+
}), [
|
|
1449
|
+
state,
|
|
1450
|
+
machine,
|
|
1451
|
+
targetProps
|
|
1452
|
+
]);
|
|
1453
|
+
}
|
|
1454
|
+
//#endregion
|
|
792
1455
|
exports.CopyFailure = CopyFailure;
|
|
793
1456
|
exports.CopyField = CopyField;
|
|
1457
|
+
exports.CopyGroup = CopyGroup;
|
|
794
1458
|
exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
|
|
795
1459
|
exports.DEFAULT_MIN_PENDING_MS = DEFAULT_MIN_PENDING_MS;
|
|
1460
|
+
exports.DEFAULT_PASTE_ACCEPT = DEFAULT_PASTE_ACCEPT;
|
|
1461
|
+
exports.DEFAULT_PASTE_MAX_BYTES = DEFAULT_PASTE_MAX_BYTES;
|
|
1462
|
+
exports.DEFAULT_PASTE_MAX_ITEMS = DEFAULT_PASTE_MAX_ITEMS;
|
|
796
1463
|
exports.DEFAULT_PENDING_DELAY_MS = DEFAULT_PENDING_DELAY_MS;
|
|
797
1464
|
exports.DEFAULT_RESET_AFTER_MS = DEFAULT_RESET_AFTER_MS;
|
|
798
1465
|
exports.IDLE_STATE = IDLE_STATE;
|
|
799
1466
|
exports.IMAGE_MIME_TYPE = IMAGE_MIME_TYPE;
|
|
800
1467
|
exports.LiveRegion = LiveRegion;
|
|
1468
|
+
exports.PASTE_IDLE_STATE = PASTE_IDLE_STATE;
|
|
1469
|
+
exports.SVG_MIME_TYPE = SVG_MIME_TYPE;
|
|
801
1470
|
exports.canRetryState = canRetryState;
|
|
1471
|
+
exports.copyFailure = copyFailure;
|
|
802
1472
|
exports.createBrowserClipboardAdapter = createBrowserClipboardAdapter;
|
|
1473
|
+
exports.createBrowserPasteAdapter = createBrowserPasteAdapter;
|
|
1474
|
+
exports.createCopyCoordinator = createCopyCoordinator;
|
|
803
1475
|
exports.createCopyError = createCopyError;
|
|
804
1476
|
exports.createCopyMachine = createCopyMachine;
|
|
1477
|
+
exports.createPasteMachine = createPasteMachine;
|
|
805
1478
|
exports.defaultCopyFieldMessages = defaultCopyFieldMessages;
|
|
806
1479
|
exports.describeCopyError = describeCopyError;
|
|
1480
|
+
exports.describePasteError = describePasteError;
|
|
807
1481
|
exports.isBlob = isBlob;
|
|
808
1482
|
exports.isCopyFailure = isCopyFailure;
|
|
809
1483
|
exports.isRetryableError = isRetryableError;
|
|
1484
|
+
exports.isTextualMimeType = isTextualMimeType;
|
|
1485
|
+
exports.matchesMimePattern = matchesMimePattern;
|
|
1486
|
+
exports.normalizeMimeType = normalizeMimeType;
|
|
810
1487
|
exports.normalizePayload = normalizePayload;
|
|
811
1488
|
exports.resolveMaxRetries = resolveMaxRetries;
|
|
1489
|
+
exports.resolvePasteReadOptions = resolvePasteReadOptions;
|
|
812
1490
|
exports.serializeJson = serializeJson;
|
|
1491
|
+
exports.sniffImageBytes = sniffImageBytes;
|
|
1492
|
+
exports.sniffImageType = sniffImageType;
|
|
813
1493
|
exports.toCopyError = toCopyError;
|
|
814
1494
|
exports.useCopy = useCopy;
|
|
815
1495
|
exports.useCopyField = useCopyField;
|
|
1496
|
+
exports.useCopyGroup = useCopyGroup;
|
|
816
1497
|
exports.useDisplayStatus = useDisplayStatus;
|
|
1498
|
+
exports.usePaste = usePaste;
|
|
817
1499
|
exports.useRevealOnInteraction = useRevealOnInteraction;
|
|
818
1500
|
exports.validatePayload = validatePayload;
|
|
819
1501
|
exports.visuallyHiddenStyle = visuallyHiddenStyle;
|