react-smart-copy 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,793 @@
1
+ "use client";
2
+ import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
+ import { jsx, jsxs } from "react/jsx-runtime";
4
+ //#region src/core/errors.ts
5
+ function createCopyError(type, message, cause) {
6
+ return cause === void 0 ? {
7
+ type,
8
+ message
9
+ } : {
10
+ type,
11
+ message,
12
+ cause
13
+ };
14
+ }
15
+ const RETRYABLE_ERRORS = /* @__PURE__ */ new Set([
16
+ "permission-denied",
17
+ "not-focused",
18
+ "blob-generation-failed",
19
+ "unknown"
20
+ ]);
21
+ /** Whether retrying the same payload could plausibly succeed. */
22
+ function isRetryableError(error) {
23
+ return RETRYABLE_ERRORS.has(error.type);
24
+ }
25
+ /**
26
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
27
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
28
+ */
29
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
30
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
31
+ var CopyFailure = class extends Error {
32
+ constructor(copyError) {
33
+ super(copyError.message);
34
+ this[COPY_FAILURE_BRAND] = true;
35
+ this.name = "CopyFailure";
36
+ this.copyError = copyError;
37
+ }
38
+ };
39
+ function isCopyFailure(value) {
40
+ return typeof value === "object" && value !== null && value[COPY_FAILURE_BRAND] === true;
41
+ }
42
+ function readString(value, key) {
43
+ if (typeof value !== "object" || value === null) return void 0;
44
+ const field = value[key];
45
+ return typeof field === "string" ? field : void 0;
46
+ }
47
+ /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
48
+ function toCopyError(cause) {
49
+ if (isCopyFailure(cause)) return cause.copyError;
50
+ const name = readString(cause, "name");
51
+ const message = readString(cause, "message") ?? "";
52
+ switch (name) {
53
+ case "NotAllowedError": return /focus/i.test(message) ? createCopyError("not-focused", "The document was not focused when the copy was attempted.", cause) : createCopyError("permission-denied", "Clipboard write permission was denied.", cause);
54
+ case "SecurityError": return createCopyError("insecure-context", "The clipboard is blocked in this context.", cause);
55
+ case "NotSupportedError":
56
+ case "DataError": return createCopyError("unsupported-format", "The browser rejected this clipboard format.", cause);
57
+ default: return createCopyError("unknown", message || "The copy failed for an unknown reason.", cause);
58
+ }
59
+ }
60
+ const DEFAULT_DESCRIPTIONS = {
61
+ unsupported: "Copying isn't supported in this browser.",
62
+ "insecure-context": "Copying requires a secure (HTTPS) connection.",
63
+ "permission-denied": "Clipboard access was blocked. Allow it and try again.",
64
+ "not-focused": "The page lost focus while copying. Try again.",
65
+ "invalid-payload": "There is nothing to copy.",
66
+ "unsupported-format": "This content can't be copied in this browser.",
67
+ "blob-generation-failed": "The image couldn't be prepared for copying.",
68
+ "max-retries-exceeded": "Copying failed after several attempts.",
69
+ unknown: "Couldn't copy to the clipboard. Try again."
70
+ };
71
+ /** Default English, user-facing sentence for an error. Replace for i18n. */
72
+ function describeCopyError(error) {
73
+ return DEFAULT_DESCRIPTIONS[error.type];
74
+ }
75
+ //#endregion
76
+ //#region src/core/payload.ts
77
+ /** The only image MIME type with reliable cross-browser clipboard write support. */
78
+ const IMAGE_MIME_TYPE = "image/png";
79
+ function normalizePayload(input) {
80
+ return typeof input === "string" ? {
81
+ kind: "text",
82
+ value: input
83
+ } : input;
84
+ }
85
+ function isBlob(value) {
86
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
87
+ const tag = Object.prototype.toString.call(value);
88
+ return tag === "[object Blob]" || tag === "[object File]";
89
+ }
90
+ function isThenable(value) {
91
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
92
+ }
93
+ const invalid = (message) => createCopyError("invalid-payload", message);
94
+ /**
95
+ * Structural validation. Typed callers can't produce most of these states,
96
+ * but plain-JS callers and runtime data can, so the check is always on.
97
+ */
98
+ function validatePayload(payload) {
99
+ if (typeof payload !== "object" || payload === null) return invalid("Copy input must be a string or a payload object.");
100
+ const candidate = payload;
101
+ switch (candidate["kind"]) {
102
+ case "text": return typeof candidate["value"] === "string" && candidate["value"].length > 0 ? null : invalid("Text payload must be a non-empty string.");
103
+ case "html":
104
+ if (typeof candidate["html"] !== "string" || candidate["html"].length === 0) return invalid("HTML payload requires a non-empty `html` string.");
105
+ return typeof candidate["text"] === "string" && candidate["text"].length > 0 ? null : invalid("HTML payload requires a non-empty plain-text `text` fallback.");
106
+ case "image": {
107
+ const source = candidate["blob"];
108
+ return isBlob(source) || typeof source === "function" || isThenable(source) ? null : invalid("Image payload requires a Blob, a Promise<Blob> or a function returning one.");
109
+ }
110
+ case "json": return candidate["value"] === void 0 ? invalid("JSON payload value is undefined.") : null;
111
+ case "multi": {
112
+ const items = candidate["items"];
113
+ if (!Array.isArray(items) || items.length === 0) return invalid("Multi payload requires at least one item.");
114
+ const seen = /* @__PURE__ */ new Set();
115
+ for (const item of items) {
116
+ const entry = typeof item === "object" && item !== null ? item : {};
117
+ const mimeType = entry["mimeType"];
118
+ const data = entry["data"];
119
+ if (typeof mimeType !== "string" || mimeType.length === 0) return invalid("Every multi item needs a non-empty `mimeType`.");
120
+ if (seen.has(mimeType)) return invalid(`Duplicate MIME type "${mimeType}" in multi payload.`);
121
+ seen.add(mimeType);
122
+ if (typeof data !== "string" && !isBlob(data)) return invalid(`Multi item "${mimeType}" must contain a string or a Blob.`);
123
+ }
124
+ return null;
125
+ }
126
+ default: return invalid(`Unknown payload kind: ${String(candidate["kind"])}.`);
127
+ }
128
+ }
129
+ /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
130
+ function serializeJson(payload) {
131
+ const indent = payload.pretty === true ? 2 : typeof payload.pretty === "number" ? payload.pretty : void 0;
132
+ let text;
133
+ try {
134
+ text = JSON.stringify(payload.value, null, indent);
135
+ } catch (cause) {
136
+ throw new CopyFailure(createCopyError("invalid-payload", "JSON payload could not be serialised (circular reference or BigInt?).", cause));
137
+ }
138
+ if (typeof text !== "string") throw new CopyFailure(createCopyError("invalid-payload", "JSON payload serialised to nothing (functions, symbols and undefined are not JSON)."));
139
+ return text;
140
+ }
141
+ //#endregion
142
+ //#region src/core/clipboard-adapter.ts
143
+ const fail = (type, message, cause) => new CopyFailure(createCopyError(type, message, cause));
144
+ const noop = () => void 0;
145
+ function defaultEnvironment() {
146
+ return typeof window === "undefined" ? void 0 : window;
147
+ }
148
+ function getRichClipboard(env, clipboard) {
149
+ const Item = env.ClipboardItem;
150
+ if (!Item || typeof clipboard.write !== "function") return null;
151
+ return {
152
+ Item,
153
+ write: clipboard.write.bind(clipboard)
154
+ };
155
+ }
156
+ function isTypeSupported(Item, type) {
157
+ return typeof Item.supports !== "function" || Item.supports(type);
158
+ }
159
+ function writeText(clipboard, text) {
160
+ if (typeof clipboard.writeText !== "function") throw fail("unsupported", "navigator.clipboard.writeText() is not available.");
161
+ return clipboard.writeText(text);
162
+ }
163
+ async function resolveImageBlob(source) {
164
+ let blob;
165
+ try {
166
+ blob = await (typeof source === "function" ? source() : source);
167
+ } catch (cause) {
168
+ throw fail("blob-generation-failed", "The image source threw or rejected while producing a Blob.", cause);
169
+ }
170
+ if (!isBlob(blob)) throw fail("blob-generation-failed", "The image source did not produce a Blob.");
171
+ if (blob.type !== "image/png") throw fail("unsupported-format", `Only ${IMAGE_MIME_TYPE} can be written to the clipboard (received "${blob.type || "unknown"}"). Convert with canvas.toBlob(cb, "${IMAGE_MIME_TYPE}").`);
172
+ return blob;
173
+ }
174
+ async function writeImage(rich, source) {
175
+ if (!isTypeSupported(rich.Item, "image/png")) throw fail("unsupported-format", `This browser cannot write ${IMAGE_MIME_TYPE} to the clipboard.`);
176
+ const blob = resolveImageBlob(source);
177
+ blob.catch(noop);
178
+ try {
179
+ await rich.write([new rich.Item({ [IMAGE_MIME_TYPE]: blob })]);
180
+ } catch (error) {
181
+ throw await blob.then(noop, (inner) => inner) ?? error;
182
+ }
183
+ }
184
+ async function writeToClipboard(payload, env, degradeHtmlToText) {
185
+ if (!env) throw fail("unsupported", "No browser environment: the clipboard only exists in the browser.");
186
+ if (env.isSecureContext === false) throw fail("insecure-context", "The Clipboard API requires a secure context (HTTPS or localhost).");
187
+ const clipboard = env.navigator?.clipboard;
188
+ if (!clipboard) throw fail("unsupported", "navigator.clipboard is not available in this browser.");
189
+ switch (payload.kind) {
190
+ case "text": return writeText(clipboard, payload.value);
191
+ case "json": return writeText(clipboard, serializeJson(payload));
192
+ case "html": {
193
+ const rich = getRichClipboard(env, clipboard);
194
+ if (!rich || !isTypeSupported(rich.Item, "text/html")) {
195
+ if (degradeHtmlToText) return writeText(clipboard, payload.text);
196
+ throw fail("unsupported-format", "Rich HTML copy requires ClipboardItem and navigator.clipboard.write().");
197
+ }
198
+ return rich.write([new rich.Item({
199
+ "text/html": new Blob([payload.html], { type: "text/html" }),
200
+ "text/plain": new Blob([payload.text], { type: "text/plain" })
201
+ })]);
202
+ }
203
+ case "image": {
204
+ const rich = getRichClipboard(env, clipboard);
205
+ if (!rich) throw fail("unsupported-format", "Image copy requires ClipboardItem and navigator.clipboard.write().");
206
+ return writeImage(rich, payload.blob);
207
+ }
208
+ case "multi": {
209
+ const rich = getRichClipboard(env, clipboard);
210
+ if (!rich) throw fail("unsupported-format", "Multi-format copy requires ClipboardItem and navigator.clipboard.write().");
211
+ const record = {};
212
+ for (const { mimeType, data } of payload.items) {
213
+ if (!isTypeSupported(rich.Item, mimeType)) throw fail("unsupported-format", `This browser cannot write "${mimeType}" to the clipboard.`);
214
+ record[mimeType] = typeof data === "string" ? new Blob([data], { type: mimeType }) : data;
215
+ }
216
+ return rich.write([new rich.Item(record)]);
217
+ }
218
+ }
219
+ }
220
+ /** The default adapter: async Clipboard API with feature detection and honest errors. */
221
+ function createBrowserClipboardAdapter(options = {}) {
222
+ const getEnvironment = options.getEnvironment ?? defaultEnvironment;
223
+ const degradeHtmlToText = options.degradeHtmlToText ?? true;
224
+ return { write: (payload) => writeToClipboard(payload, getEnvironment(), degradeHtmlToText) };
225
+ }
226
+ //#endregion
227
+ //#region src/core/copy-machine.ts
228
+ const DEFAULT_RESET_AFTER_MS = 2e3;
229
+ const DEFAULT_MAX_RETRIES = 3;
230
+ const IDLE_STATE = /* @__PURE__ */ Object.freeze({ status: "idle" });
231
+ const IGNORED_IN_FLIGHT = /* @__PURE__ */ Object.freeze({
232
+ status: "ignored",
233
+ reason: "in-flight"
234
+ });
235
+ const IGNORED_NOTHING = /* @__PURE__ */ Object.freeze({
236
+ status: "ignored",
237
+ reason: "nothing-to-retry"
238
+ });
239
+ const IGNORED_NOT_RETRYABLE = /* @__PURE__ */ Object.freeze({
240
+ status: "ignored",
241
+ reason: "not-retryable"
242
+ });
243
+ function resolveMaxRetries(value) {
244
+ if (value === Infinity) return Infinity;
245
+ if (value === void 0 || !Number.isFinite(value)) return 3;
246
+ return Math.max(0, Math.floor(value));
247
+ }
248
+ function resolveResetDelay(value) {
249
+ if (value === false || value === Infinity) return null;
250
+ if (value === void 0 || Number.isNaN(value)) return DEFAULT_RESET_AFTER_MS;
251
+ return Math.max(0, value);
252
+ }
253
+ /** Pure helper: can `retry()` do anything from this state? */
254
+ function canRetryState(state, maxRetries) {
255
+ return state.status === "error" && state.payload !== null && isRetryableError(state.error) && state.retryCount < resolveMaxRetries(maxRetries);
256
+ }
257
+ function reportCallbackError(error) {
258
+ const scope = globalThis;
259
+ if (typeof scope.reportError === "function") scope.reportError(error);
260
+ else setTimeout(() => {
261
+ throw error;
262
+ }, 0);
263
+ }
264
+ /** User callbacks must never corrupt machine state; their errors are reported, not swallowed. */
265
+ function invoke(fn, ...args) {
266
+ if (!fn) return;
267
+ try {
268
+ fn(...args);
269
+ } catch (error) {
270
+ reportCallbackError(error);
271
+ }
272
+ }
273
+ let defaultAdapter;
274
+ const getDefaultAdapter = () => defaultAdapter ?? (defaultAdapter = createBrowserClipboardAdapter());
275
+ /** Framework-agnostic copy state machine. */
276
+ function createCopyMachine(options = {}) {
277
+ const read = typeof options === "function" ? options : () => options;
278
+ const listeners = /* @__PURE__ */ new Set();
279
+ let state = IDLE_STATE;
280
+ let generation = 0;
281
+ let resetTimer;
282
+ const now = () => (read().now ?? Date.now)();
283
+ const setState = (next) => {
284
+ if (next === state) return;
285
+ state = next;
286
+ for (const listener of Array.from(listeners)) listener();
287
+ };
288
+ const clearResetTimer = () => {
289
+ if (resetTimer !== void 0) {
290
+ clearTimeout(resetTimer);
291
+ resetTimer = void 0;
292
+ }
293
+ };
294
+ const scheduleReset = (copied) => {
295
+ clearResetTimer();
296
+ const delay = resolveResetDelay(read().resetAfterMs);
297
+ if (delay === null) return;
298
+ const remaining = Math.max(0, delay - (now() - copied.at));
299
+ resetTimer = setTimeout(() => {
300
+ resetTimer = void 0;
301
+ if (state === copied) setState(IDLE_STATE);
302
+ }, remaining);
303
+ };
304
+ const settleError = (error, payload, retryCount) => {
305
+ setState({
306
+ status: "error",
307
+ payload,
308
+ error,
309
+ retryCount
310
+ });
311
+ invoke(read().onError, error, payload);
312
+ };
313
+ const run = (source, retryCount) => {
314
+ clearResetTimer();
315
+ const current = ++generation;
316
+ let payload;
317
+ try {
318
+ payload = normalizePayload(typeof source === "function" ? source() : source);
319
+ } catch (cause) {
320
+ const error = createCopyError("invalid-payload", "The copy source function threw.", cause);
321
+ settleError(error, null, retryCount);
322
+ return Promise.resolve({
323
+ status: "error",
324
+ error
325
+ });
326
+ }
327
+ const invalid = validatePayload(payload);
328
+ if (invalid) {
329
+ settleError(invalid, payload, retryCount);
330
+ return Promise.resolve({
331
+ status: "error",
332
+ error: invalid
333
+ });
334
+ }
335
+ setState({
336
+ status: "copying",
337
+ payload,
338
+ retryCount
339
+ });
340
+ let pending;
341
+ try {
342
+ pending = (read().adapter ?? getDefaultAdapter()).write(payload);
343
+ } catch (cause) {
344
+ pending = Promise.reject(cause);
345
+ }
346
+ return pending.then(() => {
347
+ if (current === generation) {
348
+ const copied = {
349
+ status: "copied",
350
+ payload,
351
+ at: now()
352
+ };
353
+ setState(copied);
354
+ scheduleReset(copied);
355
+ invoke(read().onCopy, payload);
356
+ }
357
+ return {
358
+ status: "copied",
359
+ payload
360
+ };
361
+ }, (cause) => {
362
+ const error = toCopyError(cause);
363
+ if (current === generation) settleError(error, payload, retryCount);
364
+ return {
365
+ status: "error",
366
+ error
367
+ };
368
+ });
369
+ };
370
+ const copy = (source) => state.status === "copying" ? Promise.resolve(IGNORED_IN_FLIGHT) : run(source, 0);
371
+ const retry = () => {
372
+ if (state.status !== "error") return Promise.resolve(IGNORED_NOTHING);
373
+ if (state.payload === null || !isRetryableError(state.error)) return Promise.resolve(IGNORED_NOT_RETRYABLE);
374
+ if (state.retryCount >= resolveMaxRetries(read().maxRetries)) {
375
+ const error = createCopyError("max-retries-exceeded", `Copy failed after ${String(state.retryCount)} retries.`, state.error);
376
+ settleError(error, state.payload, state.retryCount);
377
+ return Promise.resolve({
378
+ status: "error",
379
+ error
380
+ });
381
+ }
382
+ return run(state.payload, state.retryCount + 1);
383
+ };
384
+ const reset = () => {
385
+ ++generation;
386
+ clearResetTimer();
387
+ setState(IDLE_STATE);
388
+ };
389
+ const connect = () => {
390
+ if (state.status === "copied") scheduleReset(state);
391
+ return () => {
392
+ ++generation;
393
+ clearResetTimer();
394
+ if (state.status === "copying") setState(IDLE_STATE);
395
+ };
396
+ };
397
+ return {
398
+ getSnapshot: () => state,
399
+ subscribe: (listener) => {
400
+ listeners.add(listener);
401
+ return () => {
402
+ listeners.delete(listener);
403
+ };
404
+ },
405
+ copy,
406
+ retry,
407
+ reset,
408
+ connect
409
+ };
410
+ }
411
+ //#endregion
412
+ //#region src/react/utils.ts
413
+ /** `useLayoutEffect` in the browser, `useEffect` on the server (no SSR warning). */
414
+ const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
415
+ function mergeRefs(...refs) {
416
+ return (node) => {
417
+ for (const ref of refs) if (typeof ref === "function") ref(node);
418
+ else if (ref) ref.current = node;
419
+ };
420
+ }
421
+ /** Runs the consumer's handler first; ours is skipped if they call `preventDefault()`. */
422
+ function composeEventHandlers(theirs, ours) {
423
+ return (event) => {
424
+ theirs?.(event);
425
+ if (!event.defaultPrevented) ours(event);
426
+ };
427
+ }
428
+ //#endregion
429
+ //#region src/react/useCopy.ts
430
+ const getServerSnapshot$1 = () => IDLE_STATE;
431
+ /**
432
+ * Copy state machine bound to a component. Options may change on every render
433
+ * (inline callbacks are fine); the latest ones are always used.
434
+ */
435
+ function useCopy(options = {}) {
436
+ const optionsRef = useRef(options);
437
+ useIsomorphicLayoutEffect(() => {
438
+ optionsRef.current = options;
439
+ });
440
+ const [machine] = useState(() => createCopyMachine(() => optionsRef.current));
441
+ useEffect(() => machine.connect(), [machine]);
442
+ const state = useSyncExternalStore(machine.subscribe, machine.getSnapshot, getServerSnapshot$1);
443
+ const canRetry = canRetryState(state, options.maxRetries);
444
+ return useMemo(() => ({
445
+ state,
446
+ status: state.status,
447
+ error: state.status === "error" ? state.error : null,
448
+ canRetry,
449
+ copy: machine.copy,
450
+ retry: machine.retry,
451
+ reset: machine.reset
452
+ }), [
453
+ state,
454
+ canRetry,
455
+ machine
456
+ ]);
457
+ }
458
+ //#endregion
459
+ //#region src/react/useMediaQuery.ts
460
+ const getServerSnapshot = () => false;
461
+ function getMediaQueryList(query) {
462
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(query) : null;
463
+ }
464
+ /** SSR-safe media query subscription. Server and hydration render `false`. */
465
+ function useMediaQuery(query) {
466
+ const subscribe = useCallback((onChange) => {
467
+ const list = getMediaQueryList(query);
468
+ if (!list) return () => void 0;
469
+ list.addEventListener("change", onChange);
470
+ return () => {
471
+ list.removeEventListener("change", onChange);
472
+ };
473
+ }, [query]);
474
+ const getSnapshot = useCallback(() => getMediaQueryList(query)?.matches ?? false, [query]);
475
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
476
+ }
477
+ //#endregion
478
+ //#region src/react/useRevealOnInteraction.ts
479
+ function isFocusVisible(element) {
480
+ if (!(element instanceof Element)) return true;
481
+ try {
482
+ return element.matches(":focus-visible");
483
+ } catch {
484
+ return true;
485
+ }
486
+ }
487
+ /**
488
+ * Reveals secondary actions on hover, keyboard focus and touch, and always on
489
+ * devices that cannot hover. Hover and focus are tracked independently, so a
490
+ * touchscreen laptop never gets stuck in a "touch only" mode.
491
+ *
492
+ * Keep the actions in the DOM and in the tab order; hide them visually with
493
+ * CSS keyed off `visible` (or `data-revealed`), never with `display: none`.
494
+ */
495
+ function useRevealOnInteraction(options = {}) {
496
+ const [hovered, setHovered] = useState(false);
497
+ const [focused, setFocused] = useState(false);
498
+ const [touched, setTouched] = useState(false);
499
+ const cannotHover = useMediaQuery("(hover: none)");
500
+ const nodeRef = useRef(null);
501
+ useEffect(() => {
502
+ if (!touched) return void 0;
503
+ const dismiss = (event) => {
504
+ const node = nodeRef.current;
505
+ if (node && event.target instanceof Node && node.contains(event.target)) return;
506
+ setTouched(false);
507
+ };
508
+ document.addEventListener("pointerdown", dismiss, true);
509
+ return () => {
510
+ document.removeEventListener("pointerdown", dismiss, true);
511
+ };
512
+ }, [touched]);
513
+ const targetProps = useMemo(() => ({
514
+ ref: (node) => {
515
+ nodeRef.current = node;
516
+ },
517
+ onPointerEnter: (event) => {
518
+ if (event.pointerType !== "touch") setHovered(true);
519
+ },
520
+ onPointerLeave: (event) => {
521
+ if (event.pointerType !== "touch") setHovered(false);
522
+ },
523
+ onPointerDown: (event) => {
524
+ if (event.pointerType === "touch") setTouched(true);
525
+ },
526
+ onFocus: (event) => {
527
+ setFocused(isFocusVisible(event.target));
528
+ },
529
+ onBlur: (event) => {
530
+ const next = event.relatedTarget;
531
+ if (next instanceof Node && event.currentTarget.contains(next)) return;
532
+ setFocused(false);
533
+ }
534
+ }), []);
535
+ const reason = options.alwaysVisible ? "forced" : focused ? "focus" : hovered ? "hover" : touched ? "touch" : cannotHover ? "no-hover-device" : null;
536
+ return {
537
+ visible: reason !== null,
538
+ reason,
539
+ targetProps
540
+ };
541
+ }
542
+ //#endregion
543
+ //#region src/react/useDisplayStatus.ts
544
+ const DEFAULT_PENDING_DELAY_MS = 150;
545
+ const DEFAULT_MIN_PENDING_MS = 400;
546
+ /**
547
+ * Presentation-only view of a copy status that never flickers.
548
+ *
549
+ * The real `status` is honest and can be `copying` for a single frame (text
550
+ * copies take ~1-5 ms). Rendering that directly flashes a "Copying…" label.
551
+ * This hook keeps showing the previous state during fast copies, and when a
552
+ * copy is genuinely slow it shows `copying` for a minimum time instead of a blink.
553
+ *
554
+ * It never changes the state machine: use `status` for logic, this for pixels.
555
+ */
556
+ function useDisplayStatus(status, options = {}) {
557
+ const pendingDelayMs = Math.max(0, options.pendingDelayMs ?? 150);
558
+ const minPendingMs = Math.max(0, options.minPendingMs ?? 400);
559
+ const [settled, setSettled] = useState(status === "copying" ? "idle" : status);
560
+ if (status !== "copying" && status !== settled) setSettled(status);
561
+ const [pendingShownAt, setPendingShownAt] = useState(null);
562
+ useEffect(() => {
563
+ if (status !== "copying") return void 0;
564
+ const timer = setTimeout(() => {
565
+ setPendingShownAt(Date.now());
566
+ }, pendingDelayMs);
567
+ return () => {
568
+ clearTimeout(timer);
569
+ };
570
+ }, [status, pendingDelayMs]);
571
+ useEffect(() => {
572
+ if (status === "copying" || pendingShownAt === null) return void 0;
573
+ const remaining = Math.max(0, minPendingMs - (Date.now() - pendingShownAt));
574
+ const timer = setTimeout(() => {
575
+ setPendingShownAt(null);
576
+ }, remaining);
577
+ return () => {
578
+ clearTimeout(timer);
579
+ };
580
+ }, [
581
+ status,
582
+ pendingShownAt,
583
+ minPendingMs
584
+ ]);
585
+ if (pendingShownAt !== null) return "copying";
586
+ return status === "copying" ? settled : status;
587
+ }
588
+ //#endregion
589
+ //#region src/react/LiveRegion.tsx
590
+ /** Hides content visually while keeping it available to assistive technology. */
591
+ const visuallyHiddenStyle = {
592
+ position: "absolute",
593
+ width: 1,
594
+ height: 1,
595
+ padding: 0,
596
+ margin: -1,
597
+ overflow: "hidden",
598
+ clip: "rect(0, 0, 0, 0)",
599
+ whiteSpace: "nowrap",
600
+ border: 0
601
+ };
602
+ /**
603
+ * Always-mounted announcer. Screen readers ignore regions that are inserted
604
+ * together with their content, so this must render before the first message.
605
+ */
606
+ function LiveRegion({ message, politeness = "polite", visuallyHidden = true, style, ...rest }) {
607
+ return /* @__PURE__ */ jsx("span", {
608
+ ...rest,
609
+ role: politeness === "assertive" ? "alert" : "status",
610
+ "aria-live": politeness,
611
+ "aria-atomic": "true",
612
+ style: visuallyHidden ? {
613
+ ...visuallyHiddenStyle,
614
+ ...style
615
+ } : style,
616
+ children: message
617
+ });
618
+ }
619
+ //#endregion
620
+ //#region src/react/CopyField.tsx
621
+ const defaultCopyFieldMessages = {
622
+ copied: "Copied to clipboard",
623
+ error: describeCopyError,
624
+ triggerLabel: (label) => `Copy ${label}`
625
+ };
626
+ const CopyFieldContext = /* @__PURE__ */ createContext(null);
627
+ /** Access field state to build custom parts. Must be used inside `<CopyField.Root>`. */
628
+ function useCopyField() {
629
+ const context = useContext(CopyFieldContext);
630
+ if (!context) throw new Error("useCopyField() must be used inside <CopyField.Root>.");
631
+ return context;
632
+ }
633
+ function getDisplayValue(value) {
634
+ if (typeof value === "string") return value;
635
+ if (typeof value === "object" && value.kind === "text") return value.value;
636
+ return null;
637
+ }
638
+ const Root = /* @__PURE__ */ forwardRef(function CopyFieldRoot({ value, label, copyOptions, messages: messageOverrides, alwaysVisible = false, announce = true, pendingDelayMs, minPendingMs, children, onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur, ...rest }, forwardedRef) {
639
+ const copyState = useCopy(copyOptions);
640
+ const displayStatus = useDisplayStatus(copyState.status, {
641
+ ...pendingDelayMs === void 0 ? {} : { pendingDelayMs },
642
+ ...minPendingMs === void 0 ? {} : { minPendingMs }
643
+ });
644
+ const reveal = useRevealOnInteraction({ alwaysVisible });
645
+ const baseId = useId();
646
+ const labelId = `${baseId}-label`;
647
+ const valueId = `${baseId}-value`;
648
+ const messages = useMemo(() => ({
649
+ ...defaultCopyFieldMessages,
650
+ ...messageOverrides
651
+ }), [messageOverrides]);
652
+ const { copy } = copyState;
653
+ const copyValue = useCallback(() => copy(value), [copy, value]);
654
+ const { targetProps } = reveal;
655
+ const ref = useMemo(() => mergeRefs(targetProps.ref, forwardedRef), [targetProps.ref, forwardedRef]);
656
+ const context = useMemo(() => ({
657
+ ...copyState,
658
+ label,
659
+ labelId,
660
+ valueId,
661
+ revealed: reveal.visible,
662
+ revealReason: reveal.reason,
663
+ messages,
664
+ displayValue: getDisplayValue(value),
665
+ displayStatus,
666
+ copyValue
667
+ }), [
668
+ copyState,
669
+ label,
670
+ labelId,
671
+ valueId,
672
+ reveal.visible,
673
+ reveal.reason,
674
+ messages,
675
+ value,
676
+ displayStatus,
677
+ copyValue
678
+ ]);
679
+ const { state } = copyState;
680
+ const announcement = state.status === "copied" ? messages.copied : state.status === "error" ? messages.error(state.error) : "";
681
+ return /* @__PURE__ */ jsx(CopyFieldContext.Provider, {
682
+ value: context,
683
+ children: /* @__PURE__ */ jsxs("div", {
684
+ ...rest,
685
+ ref,
686
+ "data-state": state.status,
687
+ "data-display-state": displayStatus,
688
+ "data-revealed": reveal.visible ? "" : void 0,
689
+ onPointerEnter: composeEventHandlers(onPointerEnter, targetProps.onPointerEnter),
690
+ onPointerLeave: composeEventHandlers(onPointerLeave, targetProps.onPointerLeave),
691
+ onPointerDown: composeEventHandlers(onPointerDown, targetProps.onPointerDown),
692
+ onFocus: composeEventHandlers(onFocus, targetProps.onFocus),
693
+ onBlur: composeEventHandlers(onBlur, targetProps.onBlur),
694
+ children: [children, announce ? /* @__PURE__ */ jsx(LiveRegion, { message: announcement }) : null]
695
+ })
696
+ });
697
+ });
698
+ const Label = /* @__PURE__ */ forwardRef(function CopyFieldLabel({ children, ...rest }, ref) {
699
+ const field = useCopyField();
700
+ return /* @__PURE__ */ jsx("span", {
701
+ ...rest,
702
+ ref,
703
+ id: field.labelId,
704
+ children: children ?? field.label
705
+ });
706
+ });
707
+ const Value = /* @__PURE__ */ forwardRef(function CopyFieldValue({ children, ...rest }, ref) {
708
+ const field = useCopyField();
709
+ return /* @__PURE__ */ jsx("span", {
710
+ ...rest,
711
+ ref,
712
+ id: field.valueId,
713
+ children: children ?? field.displayValue
714
+ });
715
+ });
716
+ const DEFAULT_TRIGGER_TEXT = {
717
+ idle: "Copy",
718
+ copying: "Copying…",
719
+ copied: "Copied",
720
+ error: "Retry"
721
+ };
722
+ const TRIGGER_STATUSES = [
723
+ "idle",
724
+ "copying",
725
+ "copied",
726
+ "error"
727
+ ];
728
+ /**
729
+ * Default label: every state's text is stacked in the same grid cell, so the
730
+ * button is always as wide as its longest label and never resizes (no layout
731
+ * shift). Only the active one is visible; the others crossfade out.
732
+ */
733
+ function DefaultTriggerLabel({ status }) {
734
+ const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
735
+ return /* @__PURE__ */ jsx("span", {
736
+ style: { display: "inline-grid" },
737
+ children: TRIGGER_STATUSES.map((candidate) => {
738
+ const active = candidate === status;
739
+ return /* @__PURE__ */ jsx("span", {
740
+ "data-trigger-label": candidate,
741
+ "data-active": active ? "" : void 0,
742
+ "aria-hidden": active ? void 0 : true,
743
+ style: {
744
+ gridArea: "1 / 1",
745
+ opacity: active ? 1 : 0,
746
+ visibility: active ? "visible" : "hidden",
747
+ ...reduceMotion ? {} : { transition: "opacity 150ms ease, visibility 150ms" }
748
+ },
749
+ children: DEFAULT_TRIGGER_TEXT[candidate]
750
+ }, candidate);
751
+ })
752
+ });
753
+ }
754
+ /**
755
+ * Headless compound component for a labelled, copyable value.
756
+ *
757
+ * Styling hooks on Root and Trigger:
758
+ * - `data-display-state="idle|copying|copied|error"`: flicker-free, style with this
759
+ * - `data-state`: the real, instantaneous state, for logic and tests
760
+ * - `data-revealed`: present while the trigger should be visible
761
+ */
762
+ const CopyField = {
763
+ Root,
764
+ Label,
765
+ Value,
766
+ Trigger: /* @__PURE__ */ forwardRef(function CopyFieldTrigger({ children, onClick, "aria-label": ariaLabel, ...rest }, ref) {
767
+ const field = useCopyField();
768
+ const renderProps = {
769
+ status: field.status,
770
+ displayStatus: field.displayStatus,
771
+ state: field.state,
772
+ revealed: field.revealed,
773
+ canRetry: field.canRetry
774
+ };
775
+ return /* @__PURE__ */ jsx("button", {
776
+ ...rest,
777
+ ref,
778
+ type: "button",
779
+ "aria-label": ariaLabel ?? field.messages.triggerLabel(field.label),
780
+ "data-state": field.status,
781
+ "data-display-state": field.displayStatus,
782
+ "data-revealed": field.revealed ? "" : void 0,
783
+ onClick: composeEventHandlers(onClick, () => {
784
+ field.copyValue();
785
+ }),
786
+ children: typeof children === "function" ? children(renderProps) : children ?? /* @__PURE__ */ jsx(DefaultTriggerLabel, { status: field.displayStatus })
787
+ });
788
+ })
789
+ };
790
+ //#endregion
791
+ export { CopyFailure, CopyField, DEFAULT_MAX_RETRIES, DEFAULT_MIN_PENDING_MS, DEFAULT_PENDING_DELAY_MS, DEFAULT_RESET_AFTER_MS, IDLE_STATE, IMAGE_MIME_TYPE, LiveRegion, canRetryState, createBrowserClipboardAdapter, createCopyError, createCopyMachine, defaultCopyFieldMessages, describeCopyError, isBlob, isCopyFailure, isRetryableError, normalizePayload, resolveMaxRetries, serializeJson, toCopyError, useCopy, useCopyField, useDisplayStatus, useRevealOnInteraction, validatePayload, visuallyHiddenStyle };
792
+
793
+ //# sourceMappingURL=index.js.map