preact-missing-hooks 4.2.0 → 4.4.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.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.modern.mjs +1 -1
- package/dist/index.modern.mjs.map +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.module.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/react.js +85 -0
- package/dist/useRefPrint.d.ts +39 -0
- package/docs/main.js +31 -0
- package/llm.package.json +110 -155
- package/llm.package.txt +43 -43
- package/package.json +6 -1
- package/src/index.ts +1 -0
- package/src/useRefPrint.ts +116 -0
- package/tests/useRefPrint.test.tsx +115 -0
package/llm.package.txt
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Package: preact-missing-hooks
|
|
2
|
-
Version: 4.
|
|
2
|
+
Version: 4.2.0
|
|
3
3
|
|
|
4
4
|
Description:
|
|
5
5
|
A lightweight, extendable collection of missing React-like hooks for Preact — plus fresh, powerful new ones designed specifically for modern Preact apps.
|
|
@@ -40,48 +40,48 @@ Related packages:
|
|
|
40
40
|
preact, react, react-hooks, preact/hooks
|
|
41
41
|
|
|
42
42
|
Exports:
|
|
43
|
-
- ConnectionType : TypeScript type representing the
|
|
44
|
-
- EffectiveConnectionType : TypeScript type representing the effective connection type as defined by the Network Information API.
|
|
45
|
-
- IDBController :
|
|
46
|
-
- IndexedDBConfig : Configuration object for
|
|
47
|
-
- InjectableProps :
|
|
48
|
-
- LLMConfig : Configuration object
|
|
49
|
-
- LLMPayload : Payload
|
|
50
|
-
- NetworkState : TypeScript
|
|
51
|
-
- OGType : Type definition for Open Graph metadata types
|
|
52
|
-
- PreferredTheme : A
|
|
53
|
-
- RageClickPayload :
|
|
54
|
-
- RunOptions :
|
|
55
|
-
- ThreadedWorkerMode :
|
|
56
|
-
- useClipboard (Hook) : React hook that provides access to the system clipboard, allowing reading and writing of
|
|
57
|
-
- UseClipboardOptions : TypeScript type
|
|
58
|
-
- UseClipboardReturn : TypeScript
|
|
59
|
-
- useEventBus (Hook) : A hook that provides
|
|
60
|
-
- useIndexedDB (Hook) :
|
|
61
|
-
- UseIndexedDBReturn : Return type
|
|
62
|
-
- useLLMMetadata (Hook) : React hook
|
|
63
|
-
- useMutationObserver (Hook) : A hook that
|
|
64
|
-
- UseMutationObserverOptions :
|
|
65
|
-
- useNetworkState (Hook) : React hook that returns the current network state of the
|
|
66
|
-
- usePreferredTheme (Hook) : A hook that
|
|
67
|
-
- useRageClick (Hook) : React hook that detects rapid, repeated
|
|
68
|
-
- UseRageClickOptions :
|
|
69
|
-
- useThreadedWorker (Hook) :
|
|
70
|
-
- UseThreadedWorkerOptions :
|
|
71
|
-
- UseThreadedWorkerReturn :
|
|
72
|
-
- useTransition (Hook) : A
|
|
73
|
-
- useWasmCompute (Hook) :
|
|
74
|
-
- UseWasmComputeOptions :
|
|
75
|
-
- UseWasmComputeReturn : Type definition for the return value of
|
|
76
|
-
- useWebRTCIP (Hook) :
|
|
77
|
-
- UseWebRTCIPOptions :
|
|
78
|
-
- UseWebRTCIPReturn : Return
|
|
79
|
-
- useWorkerNotifications (Hook) : React hook that subscribes to
|
|
80
|
-
- UseWorkerNotificationsOptions : Configuration
|
|
81
|
-
- UseWorkerNotificationsReturn : Return type for useWorkerNotifications hook
|
|
82
|
-
- useWrappedChildren (Hook) : A hook that wraps
|
|
83
|
-
- WorkerEventType : Enumeration
|
|
84
|
-
- WorkerNotificationEvent : Type definition for worker notification
|
|
43
|
+
- ConnectionType : TypeScript type representing the connection type as defined by the Network Information API. It includes values like 'bluetooth', 'cellular', 'ethernet', 'wifi', 'wimax', 'none', 'unknown', 'other' that indicate the physical connection type. — e.g. 'bluetooth' | 'cellular' | 'ethernet' | 'wifi' | 'wimax' | 'none' | 'unknown' | 'other'
|
|
44
|
+
- EffectiveConnectionType : TypeScript type representing the effective connection type as defined by the Network Information API. It includes values like 'slow-2g', '2g', '3g', '4g' that indicate the effective network speed the browser detects. — e.g. 'slow-2g' | '2g' | '3g' | '4g'
|
|
45
|
+
- IDBController : Controller class managing IndexedDB instance lifecycle, providing methods to open, close, and interact with the database. Use when you need programmatic control over IndexedDB operations beyond basic hooks. — params: constructor(config: IndexedDBConfig) — returns: IDBController instance with open(), close(), getStore(), and transaction methods
|
|
46
|
+
- IndexedDBConfig : Configuration object for IndexedDB operations, specifying database name, version, and store schema. Use when setting up persistent client-side storage with custom store structures. — params: { dbName: string, version?: number, stores: { name: string, keyPath?: string, autoIncrement?: boolean }[] }
|
|
47
|
+
- InjectableProps : An interface defining the props that can be injected into a component. It is used to specify the properties that can be dynamically added to a component. — params: N/A — returns: N/A
|
|
48
|
+
- LLMConfig : Configuration object for setting up an LLM client, including model details, API keys, and connection parameters. Use this to define how the LLM should behave and connect. — params: Optional: { model: string, apiKey: string, endpoint: string, temperature?: number, maxTokens?: number } — returns: A typed configuration object for LLM initialization — e.g. const config: LLMConfig = { model: 'gpt-4', apiKey: 'your-key', endpoint: 'https://api.openai.com/v1' }
|
|
49
|
+
- LLMPayload : Payload structure for sending requests to an LLM, containing the prompt, conversation context, and optional parameters. Use this to format data sent to the LLM service. — params: Optional: { prompt: string, messages?: Message[], temperature?: number, maxTokens?: number, stream?: boolean } — returns: A typed payload object for LLM requests — e.g. const payload: LLMPayload = { prompt: 'Translate to French:', messages: [{ role: 'user', content: 'Hello world' }] }
|
|
50
|
+
- NetworkState : TypeScript type representing the complete network state object returned by useNetworkState hook. It includes online status, timestamps, bandwidth information, effective connection type, round-trip time, data saver status, and connection type. — e.g. { online: boolean, since: number, downlink: number, downlinkMax: number, effectiveType: EffectiveConnectionType, rtt: number, saveData: boolean, type: ConnectionType }
|
|
51
|
+
- OGType : Type definition for Open Graph metadata types. Represents the standardized vocabulary for social media sharing metadata, used to control how content appears when shared on platforms like Facebook and Twitter.
|
|
52
|
+
- PreferredTheme : A type alias for the possible theme values ('light' or 'dark'). It is used to ensure type safety when working with theme-related values. — params: N/A — returns: N/A
|
|
53
|
+
- RageClickPayload : Interface describing the payload structure for rage click events, typically containing timestamp, element info, and click count. Used when tracking rapid repeated clicks for UX analysis or error reporting.
|
|
54
|
+
- RunOptions : Options object for controlling execution behavior of threaded operations, including timeout settings, retry logic, and error handling strategies. Used to customize how tasks run in worker threads.
|
|
55
|
+
- ThreadedWorkerMode : Enumeration defining worker modes: 'shared' for SharedWorker instances or 'dedicated' for standard Web Workers. Determines how worker threads are instantiated and shared across components.
|
|
56
|
+
- useClipboard (Hook) : React hook that provides access to the system clipboard, allowing reading and writing of clipboard content. It returns an object with methods to read and write text to the clipboard, handling browser compatibility and permissions. — params: options?: UseClipboardOptions — returns: UseClipboardReturn: { readText: () => Promise<string>, writeText: (text: string) => Promise<void> } — e.g. const { readText, writeText } = useClipboard()
|
|
57
|
+
- UseClipboardOptions : TypeScript type representing the options object for the useClipboard hook. Currently it may include configuration options for clipboard behavior, though the exact properties depend on the implementation. — e.g. {}
|
|
58
|
+
- UseClipboardReturn : TypeScript type representing the return value of the useClipboard hook. It includes readText and writeText methods that return promises for asynchronous clipboard operations. — e.g. { readText: () => Promise<string>, writeText: (text: string) => Promise<void> }
|
|
59
|
+
- useEventBus (Hook) : A hook that provides a simple event bus for component communication. It allows components to emit and listen to events without prop drilling. — params: N/A — returns: Object with emit and on methods for event handling
|
|
60
|
+
- useIndexedDB (Hook) : Hook for managing IndexedDB database operations including opening connections, reading, writing, and deleting data. Provides reactive state management for database changes and error handling. — params: dbName: string, options?: { version?: number, objectStores?: string[] } — returns: { db: IDBDatabase | null, error: Error | null, isOpen: boolean, close: () => void } — e.g. const { db, isOpen, error } = useIndexedDB('myDatabase');
|
|
61
|
+
- UseIndexedDBReturn : Return type from useIndexedDB hook containing database instance, store references, and utility methods. Use to access structured data operations and transaction capabilities within React components. — params: { db: IDBDatabase, stores: Record<string, IDBObjectStore>, transaction: (stores: string[], mode?: IDBTransactionMode) => IDBTransaction }
|
|
62
|
+
- useLLMMetadata (Hook) : React hook that retrieves metadata about the underlying LLVM/WebAssembly compilation environment. Provides information about the current runtime capabilities, version, and available features for debugging and optimization. — returns: object containing metadata properties — e.g. const metadata = useLLMMetadata()
|
|
63
|
+
- useMutationObserver (Hook) : A hook that observes DOM mutations on a given element and calls a callback when mutations occur. It is useful for reacting to changes in the DOM structure or attributes. — params: element: Element, callback: (mutations: MutationRecord[]) => void, options?: MutationObserverInit — returns: void
|
|
64
|
+
- UseMutationObserverOptions : An interface defining the options for the useMutationObserver hook. It extends MutationObserverInit and includes additional properties specific to the hook. — params: N/A — returns: N/A
|
|
65
|
+
- useNetworkState (Hook) : React hook that returns the current network state of the device, including connection type, effective connection type, and whether the device is online or offline. It uses the browser's Network Information API to provide real-time updates when the network conditions change. — params: options?: { refreshRate?: number } — returns: NetworkState: { online: boolean, since: number, downlink: number, downlinkMax: number, effectiveType: EffectiveConnectionType, rtt: number, saveData: boolean, type: ConnectionType } — e.g. const { online, type, effectiveType } = useNetworkState()
|
|
66
|
+
- usePreferredTheme (Hook) : A hook that provides the user's preferred theme (light or dark) based on system preferences or user settings. It is useful for implementing theme-aware components. — params: N/A — returns: String representing the preferred theme ('light' or 'dark')
|
|
67
|
+
- useRageClick (Hook) : React hook that detects rapid, repeated clicks on an element, commonly known as rage clicks. It helps identify user frustration by tracking multiple clicks in quick succession and provides a callback when such behavior is detected. — params: options?: { threshold?: number, timeWindow?: number, callback?: (event: MouseEvent) => void } — returns: void — e.g. useRageClick({ threshold: 3, timeWindow: 1000, callback: (event) => console.log('Rage click detected!') })
|
|
68
|
+
- UseRageClickOptions : Configuration options for the useRageClick hook, including threshold for clicks per second, timeout duration, and callback handler. Allows customization of rage click detection sensitivity and behavior.
|
|
69
|
+
- useThreadedWorker (Hook) : Hook that creates and manages a Web Worker thread for offloading heavy computations or operations. Returns worker instance and control methods for communication and lifecycle management. — params: options: UseThreadedWorkerOptions — returns: UseThreadedWorkerReturn — e.g. const { worker, postMessage, terminate } = useThreadedWorker({ worker: myWorker });
|
|
70
|
+
- UseThreadedWorkerOptions : Configuration object for useThreadedWorker hook containing worker script URL or blob, mode selection, and optional initialization parameters. Defines how the worker thread should be created and configured.
|
|
71
|
+
- UseThreadedWorkerReturn : Return type from useThreadedWorker hook containing worker instance, message posting method, event listeners, and cleanup functions. Provides complete interface for interacting with the managed worker thread.
|
|
72
|
+
- useTransition (Hook) : A hook that provides a transition state and a function to start a transition. It is used to defer non-urgent updates to avoid blocking the UI during high-priority updates. — params: options?: { timeoutMs?: number } — returns: Array containing a boolean indicating if a transition is in progress and a function to start a transition
|
|
73
|
+
- useWasmCompute (Hook) : Hook that loads and executes WebAssembly modules for high-performance computation in the browser. Use when you need to run CPU-intensive tasks like image processing, cryptography, or numerical computations without blocking the main thread. — params: options: UseWasmComputeOptions — returns: Promise resolving to Wasm module instance with exported functions
|
|
74
|
+
- UseWasmComputeOptions : Configuration object for useWasmCompute hook specifying WASM module source, imports, and execution parameters. Use to configure memory limits, import objects, and execution environment for WebAssembly modules. — params: { moduleUrl: string, imports?: Record<string, any>, memorySize?: number }
|
|
75
|
+
- UseWasmComputeReturn : Type definition for the return value of a WASM compute function. Represents the structured result of a WebAssembly-based computation, typically containing status, data, and error information.
|
|
76
|
+
- useWebRTCIP (Hook) : Hook that retrieves local WebRTC IP addresses by creating a peer connection and parsing ICE candidates. Use when you need to detect client IP addresses for WebRTC signaling or network diagnostics. — params: options?: UseWebRTCIPOptions — returns: UseWebRTCIPReturn containing ipAddresses: string[] and loading: boolean
|
|
77
|
+
- UseWebRTCIPOptions : Configuration options for useWebRTCIP hook, allowing customization of timeout duration and STUN/TURN server configuration. Use to control how long the hook waits for ICE gathering and which servers to use. — params: { timeout?: number, iceServers?: RTCIceServer[] }
|
|
78
|
+
- UseWebRTCIPReturn : Return object from useWebRTCIP hook containing detected IP addresses and loading state. Use to access the gathered IP addresses and determine when the operation is complete. — params: { ipAddresses: string[], loading: boolean }
|
|
79
|
+
- useWorkerNotifications (Hook) : React hook that subscribes to notifications from a Web Worker. Provides real-time updates from background processing tasks, allowing components to react to worker events without manual event listener management. — params: options: UseWorkerNotificationsOptions — returns: UseWorkerNotificationsReturn — e.g. const { notifications, error } = useWorkerNotifications({ worker: myWorker })
|
|
80
|
+
- UseWorkerNotificationsOptions : Configuration object type for the useWorkerNotifications hook. Specifies parameters like the worker instance, event filters, and optional callback handlers for customizing notification subscription behavior.
|
|
81
|
+
- UseWorkerNotificationsReturn : Return type for the useWorkerNotifications hook. Provides an object containing the current notifications array, error state, and optional methods for managing the subscription to worker events.
|
|
82
|
+
- useWrappedChildren (Hook) : A hook that wraps child components with additional functionality or styling. It is useful for applying consistent behavior or appearance to a group of child components. — params: children: ReactNode, wrapper: (child: ReactNode) => ReactNode — returns: ReactNode
|
|
83
|
+
- WorkerEventType : Enumeration of possible event types that can be emitted by a Web Worker. Defines the standard set of notification categories for worker-to-main-thread communication, enabling type-safe event handling.
|
|
84
|
+
- WorkerNotificationEvent : Type definition for a worker notification event object. Contains metadata about a specific event from a Web Worker, including type, timestamp, and payload data for structured communication.
|
|
85
85
|
|
|
86
86
|
Hooks:
|
|
87
87
|
- useTransition
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "preact-missing-hooks",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.0",
|
|
4
4
|
"description": "A lightweight, extendable collection of missing React-like hooks for Preact — plus fresh, powerful new ones designed specifically for modern Preact apps.",
|
|
5
5
|
"author": "Prakhar Dubey",
|
|
6
6
|
"license": "MIT",
|
|
@@ -82,6 +82,11 @@
|
|
|
82
82
|
"import": "./dist/useWorkerNotifications.module.js",
|
|
83
83
|
"require": "./dist/useWorkerNotifications.js"
|
|
84
84
|
},
|
|
85
|
+
"./useRefPrint": {
|
|
86
|
+
"types": "./dist/useRefPrint.d.ts",
|
|
87
|
+
"import": "./dist/useRefPrint.module.js",
|
|
88
|
+
"require": "./dist/useRefPrint.js"
|
|
89
|
+
},
|
|
85
90
|
"./react": {
|
|
86
91
|
"types": "./dist/index.d.ts",
|
|
87
92
|
"import": "./dist/react.module.js",
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { RefObject } from "preact";
|
|
2
|
+
import { useCallback, useRef } from "preact/hooks";
|
|
3
|
+
|
|
4
|
+
const PRINT_CLASS = "use-ref-print-target";
|
|
5
|
+
const PRINT_STYLE_ID = "use-ref-print-styles";
|
|
6
|
+
|
|
7
|
+
const PRINT_CSS = `
|
|
8
|
+
@media print {
|
|
9
|
+
body * {
|
|
10
|
+
visibility: hidden;
|
|
11
|
+
}
|
|
12
|
+
.${PRINT_CLASS},
|
|
13
|
+
.${PRINT_CLASS} * {
|
|
14
|
+
visibility: visible;
|
|
15
|
+
}
|
|
16
|
+
.${PRINT_CLASS} {
|
|
17
|
+
position: absolute !important;
|
|
18
|
+
left: 0 !important;
|
|
19
|
+
top: 0 !important;
|
|
20
|
+
width: 100% !important;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
export interface UseRefPrintOptions {
|
|
26
|
+
/**
|
|
27
|
+
* When true, the print flow is triggered so the user can choose
|
|
28
|
+
* "Save as PDF" in the native print dialog. Uses the same window.print() path.
|
|
29
|
+
*/
|
|
30
|
+
downloadAsPdf?: boolean;
|
|
31
|
+
/** Title for the print document (e.g. used when saving as PDF). */
|
|
32
|
+
documentTitle?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface UseRefPrintReturn {
|
|
36
|
+
/** Triggers native print for the section bound to the ref (opens print dialog; only that section is printed via @media print). */
|
|
37
|
+
print: () => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A Preact hook that binds a ref to a printable section and provides a function
|
|
42
|
+
* to print only that section using the native window.print() and @media print CSS.
|
|
43
|
+
* When print() is called (or user presses Ctrl+P after focusing that section), only
|
|
44
|
+
* the ref section is visible in the print layout. User can then print or save as PDF.
|
|
45
|
+
*
|
|
46
|
+
* @param printRef - Ref to the DOM element (e.g. a div) that should be printed.
|
|
47
|
+
* @param options - Optional: downloadAsPdf hint, documentTitle for the print document.
|
|
48
|
+
* @returns Object with a print() function.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```tsx
|
|
52
|
+
* function Report() {
|
|
53
|
+
* const printRef = useRef<HTMLDivElement>(null);
|
|
54
|
+
* const { print } = useRefPrint(printRef, { documentTitle: 'Report', downloadAsPdf: true });
|
|
55
|
+
* return (
|
|
56
|
+
* <div>
|
|
57
|
+
* <div ref={printRef}>Content to print or save as PDF</div>
|
|
58
|
+
* <button onClick={print}>Print / Save as PDF</button>
|
|
59
|
+
* </div>
|
|
60
|
+
* );
|
|
61
|
+
* }
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export function useRefPrint(
|
|
65
|
+
printRef: RefObject<HTMLElement | null>,
|
|
66
|
+
options: UseRefPrintOptions = {}
|
|
67
|
+
): UseRefPrintReturn {
|
|
68
|
+
const { documentTitle } = options;
|
|
69
|
+
const originalTitleRef = useRef<string>("");
|
|
70
|
+
|
|
71
|
+
const print = useCallback(() => {
|
|
72
|
+
const el = printRef.current;
|
|
73
|
+
if (!el || typeof window === "undefined" || !window.print) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Ensure print-only styles exist (once per document)
|
|
78
|
+
let styleEl = document.getElementById(
|
|
79
|
+
PRINT_STYLE_ID
|
|
80
|
+
) as HTMLStyleElement | null;
|
|
81
|
+
if (!styleEl) {
|
|
82
|
+
styleEl = document.createElement("style");
|
|
83
|
+
styleEl.id = PRINT_STYLE_ID;
|
|
84
|
+
styleEl.textContent = PRINT_CSS;
|
|
85
|
+
document.head.appendChild(styleEl);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
el.classList.add(PRINT_CLASS);
|
|
89
|
+
if (documentTitle) {
|
|
90
|
+
originalTitleRef.current = document.title;
|
|
91
|
+
document.title = documentTitle;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const cleanup = () => {
|
|
95
|
+
el.classList.remove(PRINT_CLASS);
|
|
96
|
+
if (documentTitle && originalTitleRef.current !== undefined) {
|
|
97
|
+
document.title = originalTitleRef.current;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
if ("onafterprint" in window) {
|
|
102
|
+
const onAfterPrint = () => {
|
|
103
|
+
cleanup();
|
|
104
|
+
window.removeEventListener("afterprint", onAfterPrint);
|
|
105
|
+
};
|
|
106
|
+
window.addEventListener("afterprint", onAfterPrint);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
window.print();
|
|
110
|
+
|
|
111
|
+
// Fallback cleanup if afterprint is not fired (e.g. user cancels)
|
|
112
|
+
setTimeout(cleanup, 1000);
|
|
113
|
+
}, [printRef, documentTitle]);
|
|
114
|
+
|
|
115
|
+
return { print };
|
|
116
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** @jsx h */
|
|
2
|
+
import { h } from "preact";
|
|
3
|
+
import { useRef } from "preact/hooks";
|
|
4
|
+
import { render, fireEvent } from "@testing-library/preact";
|
|
5
|
+
import { useRefPrint } from "../src/useRefPrint";
|
|
6
|
+
import { vi } from "vitest";
|
|
7
|
+
|
|
8
|
+
const PRINT_CLASS = "use-ref-print-target";
|
|
9
|
+
const PRINT_STYLE_ID = "use-ref-print-styles";
|
|
10
|
+
|
|
11
|
+
describe("useRefPrint", () => {
|
|
12
|
+
let mockPrint: ReturnType<typeof vi.fn>;
|
|
13
|
+
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
mockPrint = vi.fn();
|
|
16
|
+
vi.spyOn(globalThis.window, "print").mockImplementation(mockPrint);
|
|
17
|
+
vi.useFakeTimers();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
document.getElementById(PRINT_STYLE_ID)?.remove();
|
|
22
|
+
vi.useRealTimers();
|
|
23
|
+
vi.restoreAllMocks();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("returns a print function", () => {
|
|
27
|
+
function TestComponent() {
|
|
28
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
29
|
+
const { print } = useRefPrint(ref);
|
|
30
|
+
return (
|
|
31
|
+
<div>
|
|
32
|
+
<div ref={ref}>Content</div>
|
|
33
|
+
<button onClick={print}>Print</button>
|
|
34
|
+
</div>
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
const { getByText } = render(<TestComponent />);
|
|
38
|
+
expect(getByText("Print")).toBeDefined();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("adds print class and injects @media print styles then calls window.print when print is clicked", () => {
|
|
42
|
+
function TestComponent() {
|
|
43
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
44
|
+
const { print } = useRefPrint(ref);
|
|
45
|
+
return (
|
|
46
|
+
<div>
|
|
47
|
+
<div ref={ref} data-testid="print-area">
|
|
48
|
+
<p>Section to print</p>
|
|
49
|
+
</div>
|
|
50
|
+
<button onClick={print}>Print</button>
|
|
51
|
+
</div>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
const { getByText, getByTestId } = render(<TestComponent />);
|
|
55
|
+
const printArea = getByTestId("print-area");
|
|
56
|
+
expect(printArea).toBeTruthy();
|
|
57
|
+
|
|
58
|
+
fireEvent.click(getByText("Print"));
|
|
59
|
+
|
|
60
|
+
expect(printArea.classList.contains(PRINT_CLASS)).toBe(true);
|
|
61
|
+
const styleEl = document.getElementById(PRINT_STYLE_ID);
|
|
62
|
+
expect(styleEl).toBeTruthy();
|
|
63
|
+
expect(styleEl?.textContent).toContain("@media print");
|
|
64
|
+
expect(styleEl?.textContent).toContain(PRINT_CLASS);
|
|
65
|
+
expect(mockPrint).toHaveBeenCalled();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("does nothing when ref.current is null", () => {
|
|
69
|
+
function TestComponent() {
|
|
70
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
71
|
+
const { print } = useRefPrint(ref);
|
|
72
|
+
return <button onClick={print}>Print</button>;
|
|
73
|
+
}
|
|
74
|
+
const { getByText } = render(<TestComponent />);
|
|
75
|
+
fireEvent.click(getByText("Print"));
|
|
76
|
+
expect(mockPrint).not.toHaveBeenCalled();
|
|
77
|
+
expect(document.getElementById(PRINT_STYLE_ID)).toBeNull();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it("sets document.title when documentTitle option is provided and restores after print", () => {
|
|
81
|
+
const originalTitle = document.title;
|
|
82
|
+
function TestComponent() {
|
|
83
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
84
|
+
const { print } = useRefPrint(ref, { documentTitle: "My Report" });
|
|
85
|
+
return (
|
|
86
|
+
<div>
|
|
87
|
+
<div ref={ref}>Content</div>
|
|
88
|
+
<button onClick={print}>Print</button>
|
|
89
|
+
</div>
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const { getByText } = render(<TestComponent />);
|
|
93
|
+
fireEvent.click(getByText("Print"));
|
|
94
|
+
expect(document.title).toBe("My Report");
|
|
95
|
+
// Simulate afterprint to trigger cleanup
|
|
96
|
+
window.dispatchEvent(new Event("afterprint"));
|
|
97
|
+
expect(document.title).toBe(originalTitle);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("calls window.print when print is invoked", () => {
|
|
101
|
+
function TestComponent() {
|
|
102
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
103
|
+
const { print } = useRefPrint(ref);
|
|
104
|
+
return (
|
|
105
|
+
<div>
|
|
106
|
+
<div ref={ref}>Content</div>
|
|
107
|
+
<button onClick={print}>Print</button>
|
|
108
|
+
</div>
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
const { getByText } = render(<TestComponent />);
|
|
112
|
+
fireEvent.click(getByText("Print"));
|
|
113
|
+
expect(mockPrint).toHaveBeenCalled();
|
|
114
|
+
});
|
|
115
|
+
});
|