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.
@@ -0,0 +1,378 @@
1
+
2
+ import { ButtonHTMLAttributes, CSSProperties, FocusEventHandler, HTMLAttributes, PointerEventHandler, ReactNode, RefCallback } from "react";
3
+ //#region src/core/errors.d.ts
4
+ /**
5
+ * Every way a copy can fail, as a closed union.
6
+ *
7
+ * `CopyError.message` is developer-facing (logs, telemetry). For user-facing
8
+ * text use {@link describeCopyError} or map `type` through your own i18n layer.
9
+ */
10
+ export type CopyErrorType =
11
+ /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */
12
+ 'unsupported' |
13
+ /** Page is not served over HTTPS/localhost. Not retryable. */
14
+ 'insecure-context' |
15
+ /** Browser or user blocked the write. Also what Safari reports for a missing user gesture. */
16
+ 'permission-denied' |
17
+ /** The document lost focus mid-copy (Chromium). Retrying after refocus usually works. */
18
+ 'not-focused' |
19
+ /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */
20
+ 'invalid-payload' |
21
+ /** The browser cannot write this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
22
+ 'unsupported-format' |
23
+ /** A lazy image source threw, rejected or did not produce a Blob. */
24
+ 'blob-generation-failed' |
25
+ /** `retry()` was called after `maxRetries` was reached. Terminal. */
26
+ 'max-retries-exceeded' |
27
+ /** Anything the platform threw that we could not classify. */
28
+ 'unknown';
29
+ export interface CopyError {
30
+ readonly type: CopyErrorType;
31
+ readonly message: string;
32
+ readonly cause?: unknown;
33
+ }
34
+ export declare function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError;
35
+ /** Whether retrying the same payload could plausibly succeed. */
36
+ export declare function isRetryableError(error: CopyError): boolean;
37
+ /**
38
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
39
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
40
+ */
41
+ declare const COPY_FAILURE_BRAND: unique symbol;
42
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
43
+ export declare class CopyFailure extends Error {
44
+ readonly copyError: CopyError;
45
+ readonly [COPY_FAILURE_BRAND] = true;
46
+ constructor(copyError: CopyError);
47
+ }
48
+ export declare function isCopyFailure(value: unknown): value is CopyFailure;
49
+ /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
50
+ export declare function toCopyError(cause: unknown): CopyError;
51
+ /** Default English, user-facing sentence for an error. Replace for i18n. */
52
+ export declare function describeCopyError(error: CopyError): string;
53
+ //#endregion
54
+ //#region src/core/payload.d.ts
55
+ /** The only image MIME type with reliable cross-browser clipboard write support. */
56
+ export declare const IMAGE_MIME_TYPE = "image/png";
57
+ /**
58
+ * An image as a Blob, a promise of one, or a function producing one.
59
+ * Prefer the function form: it is invoked synchronously inside the user
60
+ * gesture, which Safari requires for async image generation.
61
+ */
62
+ export type BlobSource = Blob | PromiseLike<Blob> | (() => Blob | PromiseLike<Blob>);
63
+ export interface TextPayload {
64
+ readonly kind: 'text';
65
+ readonly value: string;
66
+ }
67
+ export interface HtmlPayload {
68
+ readonly kind: 'html';
69
+ readonly html: string;
70
+ /** Required plain-text fallback for targets that don't understand HTML. */
71
+ readonly text: string;
72
+ }
73
+ export interface ImagePayload {
74
+ readonly kind: 'image';
75
+ readonly blob: BlobSource;
76
+ }
77
+ export interface JsonPayload {
78
+ readonly kind: 'json';
79
+ readonly value: unknown;
80
+ /** `true` = 2-space indent, a number = that indent, falsy = compact. */
81
+ readonly pretty?: boolean | number;
82
+ }
83
+ export interface MultiPayloadItem {
84
+ readonly mimeType: string;
85
+ readonly data: string | Blob;
86
+ }
87
+ export interface MultiPayload {
88
+ readonly kind: 'multi';
89
+ readonly items: readonly MultiPayloadItem[];
90
+ }
91
+ export type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
92
+ export type CopyPayloadKind = CopyPayload['kind'];
93
+ /** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */
94
+ export type CopyInput = string | CopyPayload;
95
+ /**
96
+ * What `copy()` accepts. The function form is resolved synchronously at copy
97
+ * time, so it always reads the latest value without re-rendering.
98
+ */
99
+ export type CopySource = CopyInput | (() => CopyInput);
100
+ export declare function normalizePayload(input: CopyInput): CopyPayload;
101
+ export declare function isBlob(value: unknown): value is Blob;
102
+ /**
103
+ * Structural validation. Typed callers can't produce most of these states,
104
+ * but plain-JS callers and runtime data can, so the check is always on.
105
+ */
106
+ export declare function validatePayload(payload: unknown): CopyError | null;
107
+ /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
108
+ export declare function serializeJson(payload: JsonPayload): string;
109
+ //#endregion
110
+ //#region src/core/clipboard-adapter.d.ts
111
+ /** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */
112
+ export interface ClipboardLike {
113
+ writeText?(text: string): Promise<void>;
114
+ write?(items: readonly unknown[]): Promise<void>;
115
+ }
116
+ export type ClipboardItemData = Blob | PromiseLike<Blob>;
117
+ export interface ClipboardItemConstructorLike {
118
+ new (items: Record<string, ClipboardItemData>): unknown;
119
+ supports?(type: string): boolean;
120
+ }
121
+ export interface ClipboardEnvironment {
122
+ readonly isSecureContext?: boolean;
123
+ readonly navigator?: {
124
+ readonly clipboard?: ClipboardLike | undefined;
125
+ } | undefined;
126
+ readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;
127
+ }
128
+ /**
129
+ * The only thing the state machine needs. Implement it to target Electron,
130
+ * a native bridge, a test double, or anything else.
131
+ *
132
+ * Contract: start the platform write synchronously (before any `await`) so the
133
+ * browser still sees the user gesture, and reject with a `CopyFailure` when you
134
+ * can classify the error.
135
+ */
136
+ export interface ClipboardAdapter {
137
+ write(payload: CopyPayload): Promise<void>;
138
+ }
139
+ export interface BrowserClipboardAdapterOptions {
140
+ /** Defaults to `window`, read lazily at copy time (SSR-safe). */
141
+ readonly getEnvironment?: () => ClipboardEnvironment | undefined;
142
+ /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */
143
+ readonly degradeHtmlToText?: boolean;
144
+ }
145
+ /** The default adapter: async Clipboard API with feature detection and honest errors. */
146
+ export declare function createBrowserClipboardAdapter(options?: BrowserClipboardAdapterOptions): ClipboardAdapter;
147
+ //#endregion
148
+ //#region src/core/copy-machine.d.ts
149
+ export declare const DEFAULT_RESET_AFTER_MS = 2000;
150
+ export declare const DEFAULT_MAX_RETRIES = 3;
151
+ export interface IdleState {
152
+ readonly status: 'idle';
153
+ }
154
+ export interface CopyingState {
155
+ readonly status: 'copying';
156
+ readonly payload: CopyPayload;
157
+ readonly retryCount: number;
158
+ }
159
+ export interface CopiedState {
160
+ readonly status: 'copied';
161
+ readonly payload: CopyPayload;
162
+ /** Epoch ms when the write resolved. */
163
+ readonly at: number;
164
+ }
165
+ export interface ErrorState {
166
+ readonly status: 'error';
167
+ /** `null` when the input itself could not be resolved. */
168
+ readonly payload: CopyPayload | null;
169
+ readonly error: CopyError;
170
+ readonly retryCount: number;
171
+ }
172
+ export type CopyState = IdleState | CopyingState | CopiedState | ErrorState;
173
+ export type CopyStatus = CopyState['status'];
174
+ export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable';
175
+ /** What `copy()`/`retry()` resolve to. They never reject. */
176
+ export type CopyOutcome = {
177
+ readonly status: 'copied';
178
+ readonly payload: CopyPayload;
179
+ } | {
180
+ readonly status: 'error';
181
+ readonly error: CopyError;
182
+ } | {
183
+ readonly status: 'ignored';
184
+ readonly reason: CopyIgnoredReason;
185
+ };
186
+ export interface CopyMachineOptions {
187
+ /** Defaults to the browser Clipboard API adapter. */
188
+ readonly adapter?: ClipboardAdapter;
189
+ /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */
190
+ readonly resetAfterMs?: number | false;
191
+ /** Max `retry()` calls after the first failure. Default 3. */
192
+ readonly maxRetries?: number;
193
+ readonly onCopy?: (payload: CopyPayload) => void;
194
+ readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
195
+ /** Clock injection for tests and deterministic environments. */
196
+ readonly now?: () => number;
197
+ }
198
+ /** Options object, or a getter so hosts (like React) can supply the latest options. */
199
+ export type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);
200
+ export interface CopyMachine {
201
+ readonly getSnapshot: () => CopyState;
202
+ readonly subscribe: (listener: () => void) => () => void;
203
+ readonly copy: (source: CopySource) => Promise<CopyOutcome>;
204
+ readonly retry: () => Promise<CopyOutcome>;
205
+ readonly reset: () => void;
206
+ /**
207
+ * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned
208
+ * cleanup clears timers, drops in-flight results and unsticks `copying`.
209
+ * Safe to call repeatedly (React StrictMode).
210
+ */
211
+ readonly connect: () => () => void;
212
+ }
213
+ export declare const IDLE_STATE: IdleState;
214
+ export declare function resolveMaxRetries(value: number | undefined): number;
215
+ /** Pure helper: can `retry()` do anything from this state? */
216
+ export declare function canRetryState(state: CopyState, maxRetries?: number): boolean;
217
+ /** Framework-agnostic copy state machine. */
218
+ export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
219
+ //#endregion
220
+ //#region src/react/useCopy.d.ts
221
+ type UseCopyOptions = CopyMachineOptions;
222
+ interface UseCopyResult {
223
+ /** Full discriminated state; narrow on `state.status`. */
224
+ readonly state: CopyState;
225
+ readonly status: CopyStatus;
226
+ readonly error: CopyError | null;
227
+ /** Whether `retry()` can do anything right now. */
228
+ readonly canRetry: boolean;
229
+ /** Stable identity. Never rejects; resolves to a `CopyOutcome`. */
230
+ readonly copy: CopyMachine['copy'];
231
+ /** Stable identity. Re-attempts the last failed payload, up to `maxRetries`. */
232
+ readonly retry: CopyMachine['retry'];
233
+ /** Stable identity. Back to `idle`, discarding any in-flight result. */
234
+ readonly reset: CopyMachine['reset'];
235
+ }
236
+ /**
237
+ * Copy state machine bound to a component. Options may change on every render
238
+ * (inline callbacks are fine); the latest ones are always used.
239
+ */
240
+ export declare function useCopy(options?: UseCopyOptions): UseCopyResult;
241
+ //#endregion
242
+ //#region src/react/useRevealOnInteraction.d.ts
243
+ /** Why the target is currently revealed, in priority order. */
244
+ type RevealReason = 'forced' | 'focus' | 'hover' | 'touch' | 'no-hover-device';
245
+ interface UseRevealOnInteractionOptions {
246
+ /** Always reveal (e.g. a "show actions" user setting). */
247
+ readonly alwaysVisible?: boolean;
248
+ }
249
+ interface RevealTargetProps<T extends HTMLElement> {
250
+ readonly ref: RefCallback<T>;
251
+ readonly onPointerEnter: PointerEventHandler<T>;
252
+ readonly onPointerLeave: PointerEventHandler<T>;
253
+ readonly onPointerDown: PointerEventHandler<T>;
254
+ readonly onFocus: FocusEventHandler<T>;
255
+ readonly onBlur: FocusEventHandler<T>;
256
+ }
257
+ interface UseRevealOnInteractionResult<T extends HTMLElement> {
258
+ readonly visible: boolean;
259
+ readonly reason: RevealReason | null;
260
+ /** Spread onto the container that owns the hidden actions. */
261
+ readonly targetProps: RevealTargetProps<T>;
262
+ }
263
+ /**
264
+ * Reveals secondary actions on hover, keyboard focus and touch, and always on
265
+ * devices that cannot hover. Hover and focus are tracked independently, so a
266
+ * touchscreen laptop never gets stuck in a "touch only" mode.
267
+ *
268
+ * Keep the actions in the DOM and in the tab order; hide them visually with
269
+ * CSS keyed off `visible` (or `data-revealed`), never with `display: none`.
270
+ */
271
+ export declare function useRevealOnInteraction<T extends HTMLElement = HTMLElement>(options?: UseRevealOnInteractionOptions): UseRevealOnInteractionResult<T>;
272
+ //#endregion
273
+ //#region src/react/useDisplayStatus.d.ts
274
+ export declare const DEFAULT_PENDING_DELAY_MS = 150;
275
+ export declare const DEFAULT_MIN_PENDING_MS = 400;
276
+ interface UseDisplayStatusOptions {
277
+ /** Only show `copying` if the copy takes longer than this. Default 150 ms. */
278
+ readonly pendingDelayMs?: number;
279
+ /** Once `copying` is shown, keep it visible at least this long. Default 400 ms. */
280
+ readonly minPendingMs?: number;
281
+ }
282
+ /**
283
+ * Presentation-only view of a copy status that never flickers.
284
+ *
285
+ * The real `status` is honest and can be `copying` for a single frame (text
286
+ * copies take ~1-5 ms). Rendering that directly flashes a "Copying…" label.
287
+ * This hook keeps showing the previous state during fast copies, and when a
288
+ * copy is genuinely slow it shows `copying` for a minimum time instead of a blink.
289
+ *
290
+ * It never changes the state machine: use `status` for logic, this for pixels.
291
+ */
292
+ export declare function useDisplayStatus(status: CopyStatus, options?: UseDisplayStatusOptions): CopyStatus;
293
+ //#endregion
294
+ //#region src/react/LiveRegion.d.ts
295
+ /** Hides content visually while keeping it available to assistive technology. */
296
+ export declare const visuallyHiddenStyle: CSSProperties;
297
+ interface LiveRegionProps extends Omit<HTMLAttributes<HTMLSpanElement>, 'children' | 'role' | 'aria-live' | 'aria-atomic'> {
298
+ /** Changing this text is what triggers the announcement. Empty string = silent. */
299
+ readonly message: string;
300
+ readonly politeness?: 'polite' | 'assertive';
301
+ readonly visuallyHidden?: boolean;
302
+ }
303
+ /**
304
+ * Always-mounted announcer. Screen readers ignore regions that are inserted
305
+ * together with their content, so this must render before the first message.
306
+ */
307
+ export declare function LiveRegion({ message, politeness, visuallyHidden, style, ...rest }: LiveRegionProps): import("react").JSX.Element;
308
+ //#endregion
309
+ //#region src/react/CopyField.d.ts
310
+ interface CopyFieldMessages {
311
+ /** Announced to screen readers on success. */
312
+ readonly copied: string;
313
+ /** Announced on failure. Defaults to {@link describeCopyError}. */
314
+ readonly error: (error: CopyError) => string;
315
+ /** Accessible name of the trigger. */
316
+ readonly triggerLabel: (label: string) => string;
317
+ }
318
+ export declare const defaultCopyFieldMessages: CopyFieldMessages;
319
+ interface CopyFieldContextValue extends UseCopyResult {
320
+ readonly label: string;
321
+ readonly labelId: string;
322
+ readonly valueId: string;
323
+ readonly revealed: boolean;
324
+ readonly revealReason: RevealReason | null;
325
+ readonly messages: CopyFieldMessages;
326
+ /** Text shown by `<CopyField.Value>` when the value is plain text; otherwise `null`. */
327
+ readonly displayValue: string | null;
328
+ /** Flicker-free status for rendering. Use `status` for logic, this for pixels. */
329
+ readonly displayStatus: CopyStatus;
330
+ /** Copies the field's current value. */
331
+ readonly copyValue: () => Promise<CopyOutcome>;
332
+ }
333
+ /** Access field state to build custom parts. Must be used inside `<CopyField.Root>`. */
334
+ export declare function useCopyField(): CopyFieldContextValue;
335
+ interface CopyFieldRootProps extends Omit<HTMLAttributes<HTMLDivElement>, 'onCopy' | 'onError'>, UseDisplayStatusOptions {
336
+ /** What to copy. Pass a function to read the latest value at click time. */
337
+ readonly value: CopySource;
338
+ /** Human label, used for the trigger's accessible name ("Copy Email"). */
339
+ readonly label: string;
340
+ readonly copyOptions?: UseCopyOptions;
341
+ readonly messages?: Partial<CopyFieldMessages>;
342
+ /** Skip hover/focus reveal and always show the trigger. */
343
+ readonly alwaysVisible?: boolean;
344
+ /** Render the built-in live region. Disable if your app has a global announcer. Default `true`. */
345
+ readonly announce?: boolean;
346
+ }
347
+ type CopyFieldLabelProps = HTMLAttributes<HTMLSpanElement>;
348
+ type CopyFieldValueProps = HTMLAttributes<HTMLSpanElement>;
349
+ interface CopyFieldTriggerRenderProps {
350
+ /** The real state. Use for logic. */
351
+ readonly status: CopyStatus;
352
+ /** Flicker-free state. Use for what you render. */
353
+ readonly displayStatus: CopyStatus;
354
+ readonly state: CopyState;
355
+ readonly revealed: boolean;
356
+ readonly canRetry: boolean;
357
+ }
358
+ interface CopyFieldTriggerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'type'> {
359
+ /** Static content, or a render function receiving the live state (icons, labels, spinners). */
360
+ readonly children?: ReactNode | ((props: CopyFieldTriggerRenderProps) => ReactNode);
361
+ }
362
+ /**
363
+ * Headless compound component for a labelled, copyable value.
364
+ *
365
+ * Styling hooks on Root and Trigger:
366
+ * - `data-display-state="idle|copying|copied|error"`: flicker-free, style with this
367
+ * - `data-state`: the real, instantaneous state, for logic and tests
368
+ * - `data-revealed`: present while the trigger should be visible
369
+ */
370
+ export declare const CopyField: {
371
+ readonly Root: import("react").ForwardRefExoticComponent<CopyFieldRootProps & import("react").RefAttributes<HTMLDivElement>>;
372
+ readonly Label: import("react").ForwardRefExoticComponent<CopyFieldLabelProps & import("react").RefAttributes<HTMLSpanElement>>;
373
+ readonly Value: import("react").ForwardRefExoticComponent<CopyFieldValueProps & import("react").RefAttributes<HTMLSpanElement>>;
374
+ readonly Trigger: import("react").ForwardRefExoticComponent<CopyFieldTriggerProps & import("react").RefAttributes<HTMLButtonElement>>;
375
+ };
376
+ //#endregion
377
+ export type { CopyFieldContextValue, CopyFieldLabelProps, CopyFieldMessages, CopyFieldRootProps, CopyFieldTriggerProps, CopyFieldTriggerRenderProps, CopyFieldValueProps, LiveRegionProps, RevealReason, RevealTargetProps, UseCopyOptions, UseCopyResult, UseDisplayStatusOptions, UseRevealOnInteractionOptions, UseRevealOnInteractionResult };
378
+ //# sourceMappingURL=index.d.ts.map