@signosoft/signpad-js 0.1.0 → 0.2.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/README.md CHANGED
@@ -1,376 +1,478 @@
1
+ # @signosoft/signpad-js
1
2
 
2
- ---
3
+ ## 📍 Table of Contents
3
4
 
4
- # @signosoft/signpad-js
5
+ | Core Concepts & Overview | Getting Started & Usage | Advanced & Support |
6
+ | :---------------------------------------- | :--------------------------------- | :---------------------------- |
7
+ | 📜 [Description](#-description) | 📦 [Installation](#-installation) | 🤝 [Feedback](#-feedback--support)|
8
+ | 🎬 [Demo](#-demo) | 🔐 [Licensing](#-get-your-license) | 📄 [License](#-license) |
9
+ | ⚙️ [Tech stack](#-tech-stack--built-with) | 🚀 [Quick Start](#-quick-start) | |
10
+ | | 📋 [Properties](#-properties) | |
11
+ | | 🧩 [Methods](#-methods) | |
12
+ | | 🎨 [Styling](#-styling--theming) | |
13
+
14
+ ## 📜 Description
15
+
16
+ `signosoft-signpad` is a powerful and flexible web component built with LitElement, designed for seamless digital signature capture integration into modern web applications. It provides a **unified interface** for working with various signature devices like **Wacom or Ugee**, supporting both stylus and mouse-based signing.
17
+
18
+ This component **works effortlessly** with any modern stack:
19
+
20
+ <p align="center">
21
+ <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/javascript/javascript-original.svg" alt="JS" width="35" height="35">
22
+ <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/react/react-original.svg" alt="React" width="35" height="35">
23
+ <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/angularjs/angularjs-original.svg" alt="Angular" width="35" height="35">
24
+ <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/vuejs/vuejs-original.svg" alt="Vue" width="35" height="35">
25
+ </p>
26
+
27
+ It expertly handles the complexities of **WebHID device connections**, signature session lifecycles, and high-fidelity stroke rendering.
28
+ <br/>
29
+
30
+ ## 🎬 Demo
31
+
32
+ <img src="./docsVideo.gif" alt="Signosoft Demo" width="500" />
33
+
34
+ ## ⚙️ Tech Stack / Built With
35
+
36
+ - [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=fff)](https://www.typescriptlang.org/)
37
+ - [![Lit](https://img.shields.io/badge/Lit-4C64FF?logo=Lit&logoColor=white)](https://lit.dev/)
38
+ - [![Vite](https://img.shields.io/badge/Vite-646CFF?logo=vite&logoColor=fff)](https://vitejs.dev/)
39
+ <br/>
40
+
41
+ ## 🔐 Get your license
42
+
43
+ To use the Signosoft Signpad component and its hardware drivers, a valid license key is **required**.
44
+
45
+ #### 🛑 CRITICAL: Mandatory Initialization
46
+
47
+ Without a valid license key, the component <b>WILL NOT INITIALIZE</b> and all hardware communication features will be <b>disabled</b>.
5
48
 
6
- [![npm version](https://badge.fury.io/js/%40signosoft%2Fsignpad-js.svg)](https://www.npmjs.com/package/@signosoft)
7
- [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](LICENSE)
49
+ ### 1. How to obtain a license:
8
50
 
9
- A LitElement web component for capturing signatures using a tablet (like Wacom) or mouse input, integrating seamlessly with the Signosoft signature driver powered by WebAssembly.
51
+ 1. Go to [www.signosoft.com](https://www.signosoft.com)
52
+ 2. **Sign in** to your account.
53
+ 3. Navigate to **Settings** > **Get License**.
54
+ 4. Click **Generate API Key** (License Key).
55
+ 5. Copy your key and add it to your configuration.
10
56
 
11
- ## Table of Contents
57
+ ### 2. Implementation:
12
58
 
13
- - [Features](#features)
14
- - [Installation](#installation)
15
- - [Usage](#usage)
16
- - [Basic HTML Integration](#basic-html-integration)
17
- - [JavaScript Integration](#javascript-integration)
18
- - [Properties](#properties)
19
- - [Events](#events)
20
- - [Public Methods](#public-methods)
21
- - [Retrieving the Signature Image](#retrieving-the-signature-image)
22
- - [Styling](#styling)
59
+ Add the key to the `licenseKey` field in your configuration object:
23
60
 
24
- ## Features
61
+ ```typescript
62
+ const config: SignpadConfig = {
63
+ licenseKey: "YOUR-LICENSE-KEY-HERE", // Required
64
+ // ... other options
65
+
66
+ // For local development, ensure your license is valid for localhost.
67
+ };
68
+ ```
25
69
 
26
- - **Plug-and-Play Web Component:** Easily integrate into any web application or framework.
27
- - **Wacom Tablet Integration:** Connects with Signosoft's signature driver for high-fidelity pen input from supported tablets, utilizing WebAssembly for driver communication.
28
- - **Mouse Input Fallback:** Provides a seamless fallback to mouse input if a tablet is not connected or detected.
29
- - **Customizable UI:** Control visibility of top/bottom bars, action buttons (OK, Clear, Cancel), and text elements.
30
- - **Styling Flexibility:** Apply custom CSS variables to match your application's theme.
31
- - **Event-Driven:** Emits custom events for pen movements, signature actions (OK, Clear, Cancel), and connection status.
32
- - **TypeScript Support:** Fully typed for a robust development experience.
70
+ <br/>
33
71
 
34
- ## Installation
72
+ ## 📦 Installation
35
73
 
36
- You can install the component via npm:
74
+ Install the library via npm:
37
75
 
38
76
  ```bash
39
77
  npm install @signosoft/signpad-js
40
78
  ```
41
79
 
42
- ## Usage
43
-
44
- ### Basic HTML Integration
45
-
46
- Once installed, you can simply include the component in your HTML. Make sure your build process (e.g., Vite) correctly bundles the component for browser usage.
47
-
48
- ```html
49
- <signosoft-signpad
50
- licenseKey="YOUR_BACKEND_LICENSE_KEY_HERE"
51
- .okButton="${async () => console.log("OK Button Pressed from outside!")}
52
- .clearButton=${async () => console.log("Clear Button Pressed from outside!")}
53
- .cancelButton=${async () => console.log("Cancel Button Pressed from outside!")}
54
-
55
- @sign-ok=${(e: CustomEvent<{ imageData: string | null }>) => { // Updated event detail type
56
- console.log("Signature OK event:", e.detail.imageData ? "Image data available." : "No image data.");
57
- // You can now access e.detail.imageData here
58
- }}
59
- @sign-clear=${() => console.log("Signature Clear event.")}
60
- @sign-cancel=${() => console.log("Signature Cancel event.")}
61
- @sign-pen=${(e: CustomEvent) => { /* console.log('Pen data:', e.detail) */ }}
62
- @sign-disconnect=${() => console.log("Device disconnected!")}
63
- @sign-error=${(e: CustomEvent) => console.error("Signpad error:", e.detail)}
64
- </signosoft-signpad>
65
- <button
66
- onclick="document.querySelector('signosoft-signpad').connectTablet(true)"
67
- >
68
- External Connect
69
- </button>
70
- <button
71
- onclick="document.querySelector('signosoft-signpad').disconnectTablet()"
72
- >
73
- External Disconnect
74
- </button>
75
- <button onclick="document.querySelector('signosoft-signpad').clear()">
76
- External Clear
77
- </button>
78
- <button onclick="document.querySelector('signosoft-signpad').ok()">
79
- External OK
80
- </button>
81
- <button onclick="document.querySelector('signosoft-signpad').cancel()">
82
- External Cancel
83
- </button>
80
+ Or using your preferred manager:
81
+
82
+ ```bash
83
+ yarn add @signosoft/signpad-js
84
84
  ```
85
85
 
86
- Note: Remember to replace `YOUR_BACKEND_LICENSE_KEY_HERE` with your actual backend license key for the Signosoft driver. The paths to the script might need adjustment based on your specific project setup and how you bundle the component.
86
+ ```bash
87
+ pnpm add @signosoft/signpad-js
88
+ ```
87
89
 
88
- ### JavaScript Integration
90
+ ### 🌍 Environment Requirements
89
91
 
90
- You can also interact with the component programmatically:
92
+ To ensure proper communication via the **WebHID API**:
91
93
 
92
- ```typescript
93
- import { SignosoftSignpad } from "@signosoft/signpad-js";
94
+ - **HTTPS:** Required for all production environments (WebHID security policy).
95
+ - **Supported Browsers:** Chrome 89+, Edge 89+, Opera (Chromium-based).
96
+ - **TypeScript:** Built-in support; no extra `@types` needed.
97
+ <br/>
94
98
 
95
- // If you're using a bundler (like Vite, Webpack), the component might be automatically registered.
96
- // If not, or for explicit registration, you can do:
97
- if (!customElements.get("signosoft-signpad")) {
98
- customElements.define("signosoft-signpad", SignosoftSignpad);
99
- }
99
+ ## 🚀 Quick Start
100
100
 
101
- const signpad = document.createElement("signosoft-signpad") as SignosoftSignpad;
102
- signpad.licenseKey = "YOUR_BACKEND_LICENSE_KEY_HERE";
103
- signpad.topBarVisible = true;
104
- signpad.bottomBarVisible = true;
105
- signpad.minThickness = 2;
106
- signpad.maxThickness = 8;
107
- signpad.penColor = "blue";
108
-
109
- // Assign callback functions for internal button actions
110
- signpad.OkButton = async () => {
111
- console.log("Custom OK action triggered!");
112
- // This callback runs *after* the sign-ok event is dispatched with imageData.
113
- // You might not need to retrieve the image here if you listen to the 'sign-ok' event.
114
- };
101
+ First, install the core package:
115
102
 
116
- signpad.ClearButton = async () => {
117
- console.log("Custom Clear action triggered!");
118
- };
103
+ ```bash
104
+ npm install your-library-name
105
+ ```
119
106
 
120
- signpad.CancelButton = async () => {
121
- console.log("Custom Cancel action triggered!");
122
- };
107
+ ### Framework Integration Guide
123
108
 
124
- // Listen for custom events
125
- signpad.addEventListener("sign-ok", (event: CustomEvent<{ imageData: string | null }>) => {
126
- console.log("Signature confirmed. Image data available:", !!event.detail.imageData);
127
- // event.detail.imageData now contains the Base64 image string
128
- if (event.detail.imageData) {
129
- const imgElement = document.getElementById('mySignatureDisplay') as HTMLImageElement;
130
- if (imgElement) {
131
- imgElement.src = event.detail.imageData;
132
- imgElement.style.display = 'block';
133
- }
134
- }
135
- });
136
- signpad.addEventListener("sign-error", (event) => {
137
- console.error("An error occurred:", event.detail);
138
- });
139
- signpad.addEventListener("sign-pen", (event) => {
140
- // console.log('Pen data:', event.detail);
141
- });
109
+ Choose your framework to see the full setup guide:
110
+ | Framework | Setup Guide | Status |
111
+ | :--- | :--- | :--- |
112
+ | <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/angularjs/angularjs-original.svg" alt="Angular" width="15" height="15"> **Angular** | [Docs →](./framework-docs/integration-angular.md) | <font color="green">**Live**</font> |
113
+ | <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/react/react-original.svg" alt="React" width="15" height="15"> **React** | [Docs →](./framework-docs/integration-react.md) | <font color="green">**Live**</font> |
114
+ | <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/vuejs/vuejs-original.svg" alt="Vue" width="15" height="15"> **Vue.js** | [Docs →](./framework-docs/integration-vue.md) | <font color="green">**Live**</font> |
115
+ | <img src="https://cdn.jsdelivr.net/gh/devicons/devicon/icons/javascript/javascript-original.svg" alt="JS" width="15" height="15"> **Vanilla JS** | [Docs →](./framework-docs/integration-vanilla.md) | <font color="green">**Live**</font> |
142
116
 
143
- document.body.appendChild(signpad);
117
+ ## 📋 Properties
144
118
 
145
- // Programmatically connect the tablet
146
- async function connectAndSign() {
147
- const connected = await signpad.connectTablet(true); // Attempt auto-connect
148
- if (connected) {
149
- console.log("Tablet connected and ready for signing!");
150
- } else {
151
- console.warn("Could not connect to tablet.");
152
- }
153
- }
119
+ The component is primarily configured through a single `config` property. This object controls everything from licensing and hardware behavior to UI visibility and localization.
154
120
 
155
- connectAndSign();
121
+ | Property | Type | Default | Description |
122
+ | :------- | :-------------- | :---------- | :----------------------------------------------- |
123
+ | `config` | `SignpadConfig` | `undefined` | The main configuration object for the component. |
156
124
 
157
- // To disconnect later:
158
- // await signpad.disconnectTablet();
159
- ```
125
+ ### 🔑 Core Options
126
+
127
+ | Option | Type | Required | Description |
128
+ | :------------------- | :------- | :------- | :-------------------------------------------------------------------- |
129
+ | **`licenseKey`** | `string` | **Yes** | Your unique API key from signosoft.com. Mandatory for initialization. |
130
+ | `customCssVariables` | `object` | No | Custom theme object generated via the `getSignpadTheme` utility. |
131
+
132
+ ### 🔄 autoconnectOptions
133
+
134
+ Controls how the component handles hardware connections and session flow.
135
+
136
+ | Field | Type | Default | Description |
137
+ | :------------------------------ | :-------- | :------ | :---------------------------------------------------------------------------------------------------- |
138
+ | `autoConnect` | `boolean` | `false` | Attempts to connect to an authorized device on startup. Defaults to mouse mode if no device is found. |
139
+ | `autoConnectOnPlugIn` | `boolean` | `false` | Automatically initiates connection when a compatible and authorized device is plugged into USB. |
140
+ | `autoRestartSigningAfterAction` | `boolean` | `false` | Automatically calls `startSigning()` after a user completes an action (OK/Cancel). |
141
+
142
+ ### 👁️ uiVisibilityOptions
143
+
144
+ Toggles the visibility of specific User Interface elements.
145
+
146
+ | Field | Type | Description |
147
+ | :------------------------- | :-------- | :-------------------------------------------------------------- |
148
+ | `topBarVisible` | `boolean` | Shows/hides the entire top navigation bar. |
149
+ | `topBarClearButtonVisible` | `boolean` | Shows a "Clear" button in the top-left corner. |
150
+ | `bottomBarVisible` | `boolean` | Shows/hides the entire bottom action bar. |
151
+ | `okButtonVisible` | `boolean` | Shows the **OK** button in the bottom bar. |
152
+ | `clearButtonVisible` | `boolean` | Shows the **Clear** button in the bottom bar. |
153
+ | `cancelButtonVisible` | `boolean` | Shows the **Cancel** button in the bottom bar. |
154
+ | `canvasLineVisible` | `boolean` | Shows the horizontal signature guide line on the canvas. |
155
+ | `deviceStatusTextVisible` | `boolean` | Shows the name of the connected device (e.g., "Wacom STU-540"). |
156
+ | `additionalTextVisible` | `boolean` | Shows helper status messages (e.g., "Ready to sign"). |
157
+
158
+ ### 🖋️ canvasAndDrawingOptions
159
+
160
+ Adjusts the visual appearance of the digital ink.
161
+
162
+ | Field | Type | Default | Description |
163
+ | :--------- | :------- | :-------- | :------------------------------------------ |
164
+ | `color` | `string` | `#000000` | The HEX color of the signature stroke. |
165
+ | `minWidth` | `number` | `1` | The line thickness at minimum pen pressure. |
166
+ | `maxWidth` | `number` | `3` | The line thickness at maximum pen pressure. |
167
+
168
+ > Note: Since standard mice do not support physical pressure, the system emulates a normalized pressure of 0.5, ensuring consistent line rendering during fallback sessions.
169
+
170
+ ### 🌐 languageOptions
160
171
 
161
- ## Properties
162
-
163
- You can customize the component's behavior and appearance using the following properties:
164
-
165
- | Property | Type | Default Value | Description |
166
- | :----------------------- | :--------------------------------- | :-------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
167
- | `licenseKey` | `string` | `"DEBUG-licence-backend-key-localhost"` | Backend license key for the signature driver. **Crucial for driver functionality.** |
168
- | `topBarVisible` | `boolean` | `true` | Controls the visibility of the top action bar (containing Clear, Disconnect/Connect buttons). |
169
- | `bottomBarVisible` | `boolean` | `true` | Controls the visibility of the bottom action bar (containing OK, Clear, Cancel buttons). |
170
- | `okButtonVisible` | `boolean` | `true` | Controls the visibility of the 'OK' button in the bottom bar. |
171
- | `clearButtonVisible` | `boolean` | `true` | Controls the visibility of the 'Clear' button in the bottom bar. |
172
- | `cancelButtonVisible` | `boolean` | `true` | Controls the visibility of the 'Cancel' button in the bottom bar. |
173
- | `canvasLineVisible` | `boolean` | `true` | Controls the visibility of the line on the canvas that separates device state/additional text. |
174
- | `deviceStateTextVisible` | `boolean` | `true` | Controls the visibility of the device state text in the canvas footer. |
175
- | `customDeviceStateText` | `string \| null` | `null` | Optional custom text to display for the device state, overriding the default. |
176
- | `minThickness` | `number` | `1` | Minimum pen stroke thickness in pixels. |
177
- | `maxThickness` | `number` | `5` | Maximum pen stroke thickness in pixels (at full pressure). |
178
- | `penColor` | `string` | `"#000000"` | Pen stroke color (CSS color, e.g., `'#000000'` or `'red'`). |
179
- | `customCssVariables` | `Record<string, string>` | `{}` | An object containing CSS custom property names as keys and their values as strings. These will be applied directly to the component's host element for styling customization. E.g., `{ "--signpad-canvas-bg": "#f9f9f9" }`. |
180
- | `OkButton` | `() => Promise<void> \| undefined` | `undefined` | Optional callback function (async or sync) to execute when the public `ok()` method is called, either internally or externally. It runs *after* the component's internal processing and `sign-ok` event dispatch. |
181
- | `ClearButton` | `() => Promise<void> \| undefined` | `undefined` | Optional callback function (async or sync) to execute when the public `clear()` method is called, either internally or externally. It runs after the component's internal processing. |
182
- | `CancelButton` | `() => Promise<void> \| undefined` | `undefined` | Optional callback function (async or sync) to execute when the public `cancel()` method is called, either internally or externally. It runs after the component's internal processing. |
183
- | `canvasAdditionalText` | `string \| null` | `null` | Optional additional text to display in the canvas footer. If `null` or empty, a default text will be shown. Default behavior is "Connect your device to start signing" when disconnected/error, and "Sign with [device name]" when connected. |
184
-
185
- ## Events
186
-
187
- The component dispatches several [custom events](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) that you can listen for:
188
-
189
- | Event Name | Detail Type (`event.detail`) | Description |
190
- | :---------------- | :--------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
191
- | `sign-pen` | `PenData` | Fired on every pen movement (Wacom or mouse) with `penData` (x, y, pressure, inContact, etc.). |
192
- | `sign-clear` | `void` | Fired when the signature is cleared (via internal UI button, tablet event, or `clear()` method). |
193
- | `sign-cancel` | `void` | Fired when the signature process is cancelled (via internal UI button, tablet event, or `cancel()` method). |
194
- | `sign-ok` | `{ imageData: string \| null }` | Fired when the 'OK' action is completed (via internal UI button, tablet event, or `ok()` method). The `event.detail` will contain an object with the key `imageData`, holding the Base64 encoded string of the signature from the canvas. This is dispatched *before* the component is disconnected and cleared. |
195
- | `sign-disconnect` | `void` | Fired if the tablet unexpectedly disconnects. |
196
- | `sign-error` | `Error` | Fired when an error occurs during connection or initialization, or any other critical issue. The `event.detail` will contain an `Error` object. |
197
-
198
- ## Public Methods
199
-
200
- You can programmatically control the component using its public methods:
201
-
202
- | Method | Arguments | Returns | Description |
203
- | :-------------------------- | :-------------------------------------------------------------------------------------- | :----------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
204
- | `connectTablet()` | `autoConnect?: boolean` (default: `false`), `allowFallback: boolean` (default: `false`) | `Promise<boolean>` | Connects to the signature tablet. This involves obtaining a license, initializing the signature layer, connecting to the device, and starting the signing process. If `autoConnect` is `true`, it attempts to select the first available device automatically. Returns `true` on success, `false` otherwise. |
205
- | `disconnectTablet()` | `void` | `Promise<void>` | Disconnects from the signature tablet and resets its state. |
206
- | `clear()` | `void` | `Promise<void>` | Clears the current signature from both the tablet's screen and the component's canvas. Invokes the optional `ClearButton` external callback (if provided) and then dispatches a `sign-clear` custom event. |
207
- | `ok()` | `void` | `Promise<void>` | Handles the 'OK' action, typically stopping the signing process. Retrieves the signature image data from the canvas, dispatches it via the `sign-ok` event, then executes the optional `OkButton` callback, and finally disconnects the component. |
208
- | `cancel()` | `void` | `Promise<void>` | Handles the 'Cancel' action, which typically clears any drawn signature and stops the signing process. If a `CancelButton` callback function is provided, it will be executed. Finally, a `sign-cancel` custom event is dispatched. |
209
- | `getSignatureImageBase64()` | `format?: string` (default: `'image/png'`), `quality?: number` | `string \| null` | Retrieves the current signature drawn on the canvas as a Base64 encoded image string. `format` specifies the image type (e.g., `'image/png'`, `'image/jpeg'`). `quality` (0-1) applies to `'image/jpeg'` or `'image/webp'`. Returns `null` if the canvas is not available or no drawing has started. |
210
- | `downloadSignatureImage()` | `filename?: string` (default: `'signature.png'`), `format?: string`, `quality?: number` | `void` | Triggers a download of the current signature drawn on the canvas as an image file. Uses `getSignatureImageBase64()` internally. |
211
-
212
- ## Retrieving the Signature Image
213
-
214
- There are two primary ways to retrieve the signature image from the `signosoft-signpad` component:
215
-
216
- ### 1. Using the `sign-ok` Event (Recommended for post-signing actions)
217
-
218
- When the user confirms their signature by pressing the "OK" button (either on the tablet or in the UI), the component dispatches a `sign-ok` custom event. This event's `detail` property now includes the Base64 encoded string of the signature image. This is the most common and robust way to get the final signature for submission or display.
172
+ Handles component localization. It can load external files or use inline definitions.
173
+
174
+ | Field | Type | Description |
175
+ | :------------- | :------- | :---------------------------------------------------------------------------------------------------- |
176
+ | `lang` | `string` | The active language code (supported languages - `'en'`, `'cs'`, `'pt'`). |
177
+ | `langPath` | `string` | URL path to fetch translation files. Expects files in `[path]/[lang].json` format. |
178
+ | `translations` | `object` | An inline object containing key-value pairs (e.g., `{ "OK": "Confirm signature" }`). Overrides files. |
179
+
180
+ ### ⚙️ Logic & Events
181
+
182
+ The component provides two ways to interact with internal processes.
183
+
184
+ #### 🛠️ Action Handlers (`actionHandlers`)
185
+
186
+ These allow you to **inject custom logic** directly into the internal button flows. Your code runs alongside the component's internal logic.
187
+
188
+ | Handler | Arguments | Description |
189
+ | :------------- | :----------- | :---------------------------------------------------------------------- |
190
+ | `handleOk` | `data?: any` | Extends the internal OK button logic. Receives captured signature data. |
191
+ | `handleClear` | | Extends the internal Clear button logic. |
192
+ | `handleCancel` | | Extends the internal Cancel button logic. |
193
+
194
+ #### 🔔 Event Callbacks (`eventCallbacks`)
195
+
196
+ Standard event listeners triggered _after_ specific actions. Useful for observing the component from your application state.
197
+
198
+ | Callback | Payload | Description |
199
+ | :------------- | :------------------------------ | :------------------------------------------------------------------------------------------------- |
200
+ | `onPen` | `event: CustomEvent<IPenData> ` | Dispatched when a device or mouse fallback are in contact with component or signature pad display. |
201
+ | `onConnect` | `event: CustomEvent` | Dispatched when a device or mouse fallback connects. |
202
+ | `onDisconnect` | | Dispatched when the hardware connection is closed. |
203
+ | `onOk` | `data: any` | Dispatched when signature is confirmed. |
204
+ | `onClear` | | Dispatched when the canvas has been cleared. |
205
+ | `onCancel` | | Dispatched when the user aborts the session. |
206
+ | `onError` | `error: Error` | Dispatched on critical failures (License, Driver, etc.). |
207
+
208
+ ---
209
+
210
+ ### 💡 Example Implementation
219
211
 
220
212
  ```typescript
221
- import { SignosoftSignpad } from "@signosoft/signpad-js";
222
-
223
- const signpadElement = document.querySelector('signosoft-signpad') as SignosoftSignpad;
224
-
225
- if (signpadElement) {
226
- signpadElement.addEventListener('sign-ok', (event: CustomEvent<{ imageData: string | null }>) => {
227
- const signatureBase64 = event.detail.imageData;
228
-
229
- if (signatureBase64) {
230
- console.log("Signature captured successfully (Base64 string length:", signatureBase64.length, ")");
231
-
232
- // Example 1: Display the image in an <img> tag
233
- const imgElement = document.getElementById('signatureDisplay') as HTMLImageElement;
234
- if (imgElement) {
235
- imgElement.src = signatureBase64;
236
- imgElement.style.display = 'block';
237
- }
238
-
239
- // Example 2: Send the Base64 string to your backend server
240
- /*
241
- fetch('/api/save-signature', {
242
- method: 'POST',
243
- headers: { 'Content-Type': 'application/json' },
244
- body: JSON.stringify({ signature: signatureBase64 }),
245
- })
246
- .then(response => response.json())
247
- .then(data => console.log('Signature saved on server:', data))
248
- .catch(error => console.error('Error saving signature:', error));
249
- */
250
-
251
- } else {
252
- console.warn("No signature image data was available after 'OK' action.");
253
- }
254
- });
255
-
256
- // Remember to handle other events like 'sign-clear' to clear the displayed image
257
- signpadElement.addEventListener('sign-clear', () => {
258
- const imgElement = document.getElementById('signatureDisplay') as HTMLImageElement;
259
- if (imgElement) {
260
- imgElement.src = '';
261
- imgElement.style.display = 'none';
262
- }
263
- });
264
- }
213
+ this.config = {
214
+ licenseKey: "your-signosoft-license-key",
215
+ autoconnectOptions: {
216
+ autoConnect: true,
217
+ },
218
+ canvasAndDrawingOptions: {
219
+ color: "#1a1a1a",
220
+ },
221
+ actionHandlers: {
222
+ handleOk: async (data) => {
223
+ console.log("Saving signature data...", data);
224
+ },
225
+ },
226
+ eventCallbacks: {
227
+ onConnect: (e) =>
228
+ console.log("Pad connected:", e.detail.deviceInfo.deviceName),
229
+ onError: (err) => console.error("Signpad Error:", err.message),
230
+ },
231
+ };
265
232
  ```
266
233
 
267
- ### 2. Using Public Methods (`getSignatureImageBase64` and `downloadSignatureImage`)
234
+ ## 🧩 Methods
235
+
236
+ The following methods are available on the component instance to control the signing process programmatically.
268
237
 
269
- You can also programmatically request the signature image at any time while the component is connected and drawing.
238
+ | Method | Returns | Description |
239
+ | :--------------- | :----------------- | :------------------------------------------------------------------------------- |
240
+ | `connect()` | `Promise<boolean>` | Connects device to component |
241
+ | `disconnect()` | `Promise<void>` | Disconnects device from component |
242
+ | `startSigning()` | `Promise<void>` | Initializes a new signing session on the canvas and hardware. |
243
+ | `stopSigning()` | `Promise<any>` | Immediately ends the session and returns the captured signature data. |
244
+ | `ok()` | `Promise<any>` | Finalizes the session, cleans the device screen, and returns the signature data. |
245
+ | `clear()` | `Promise<void>` | Wipes the signature from the UI and hardware without ending the session. |
246
+ | `cancel()` | `Promise<void>` | Aborts the current session and resets the component state. |
270
247
 
271
- #### `getSignatureImageBase64(format?: string, quality?: number)`
248
+ ---
249
+
250
+ #### 📜 `connect(autoConnect = false, allowFallback = false)`
251
+
252
+ This is the primary method to start using the Signpad. Because it uses the **WebHID API**, the first time this is called (without `autoConnect`), it must be triggered by a **user gesture** (like a button click) to satisfy browser security requirements.
253
+
254
+ **Parameters:**
255
+
256
+ - **`autoConnect`** (`boolean`): If set to `true`, the browser will attempt to reconnect to a previously paired and authorized device without opening the device selection dialog from WebHID.
257
+ - **`allowFallback`** (`boolean`): If `true` and no physical device is found or connected, the component will automatically transition to **Mouse/Touch mode**, allowing the user to sign using their cursor.
258
+
259
+ **Returns:**
260
+
261
+ - A `Promise<boolean>` that resolves to `true` if either a physical device or a fallback mode was successfully initialized.
262
+
263
+ #### 📜 `disconnect()`
272
264
 
273
- This method returns the signature as a Base64 encoded string.
265
+ Safely terminates the communication channel with the signature tablet.
266
+
267
+ **What happens during disconnect:**
268
+
269
+ 1. The hardware driver is stopped and released.
270
+ 2. The internal cache of device information is cleared.
271
+ 3. The component UI transitions back to the `DISCONNECTED` state.
272
+ 4. Any active mouse listeners are removed.
273
+ 5. A `SIGN_DISCONNECT` event is dispatched.
274
+
275
+ #### 💡 Best Practices
276
+
277
+ - **Initial Connection:** Always call `connect(false, true)` from a click handler the very first time so the user can select their device from the browser list.
278
+ - **Auto-Reconnect:** In many workflows, you can call `connect(true, true)`. If the user has already authorized the device in a previous session, it will connect silently.
279
+ - **Cleanup:** It is good practice to call `disconnect()` when the component is being destroyed or the user navigates away from the signing page to free up the USB port.
280
+
281
+ #### 📜 `startSigning(options?: IDrawingOptions)`
282
+
283
+ Prepares the component for a new signature. It transitions the state to `CONNECTING`, resets any previous drawing data, and activates the pen input for either a physical device or mouse fallback.
274
284
 
275
285
  ```typescript
276
- import { SignosoftSignpad } from "@signosoft/signpad-js";
286
+ // Example: Start a session with custom ink
287
+ await signpad.startSigning({
288
+ color: "#0000FF",
289
+ maxWidth: 4,
290
+ minWidth: 2,
291
+ });
292
+ ```
277
293
 
278
- const signpadElement = document.querySelector('signosoft-signpad') as SignosoftSignpad;
294
+ If you have `autoRestartSigningAfterAction` enabled in your config, the component will automatically call `startSigning()` again after an `ok` or `cancel` action is completed.
279
295
 
280
- // ... (after connecting and some drawing has occurred) ...
296
+ #### 📜 `ok()`
281
297
 
282
- if (signpadElement) {
283
- // Get as PNG (default)
284
- const pngBase64 = signpadElement.getSignatureImageBase64();
285
- if (pngBase64) {
286
- console.log("PNG Signature Base64:", pngBase64.substring(0, 50) + "...");
287
- }
298
+ This is the standard way to confirm a signature. It:
288
299
 
289
- // Get as JPEG with 80% quality
290
- const jpegBase64 = signpadElement.getSignatureImageBase64('image/jpeg', 0.8);
291
- if (jpegBase64) {
292
- console.log("JPEG Signature Base64:", jpegBase64.substring(0, 50) + "...");
293
- }
294
- }
300
+ 1. Stops the signing process.
301
+ 2. Clears the physical device's screen (if connected).
302
+ 3. Dispatches the `SIGN_OK` event.
303
+ 4. Returns the final signature payload (coordinates, pressure, metadata).
304
+
305
+ #### 📜 `stopSigning()`
306
+
307
+ A low-level method that forces the driver to stop capturing data and returns the raw signature object. Unlike `ok()`, it does not trigger the full "Finalization" flow (UI transitions or device screen clearing).
308
+
309
+ #### 📜 `clear()`
310
+
311
+ Resets the drawing state on both the web canvas and the physical tablet's display. This allows the user to start their signature over without leaving the current session. It dispatches the `SIGN_CLEAR` event.
312
+
313
+ #### 📜 `cancel()`
314
+
315
+ Stops the session immediately. It does not collect any signature data and resets the component to its ready state. This method dispatches the `SIGN_CANCEL` event.
316
+
317
+ ## 🎨 Styling & Theming
318
+
319
+ The component is designed to be fully customizable to match your brand's identity. You can style it using **CSS Variables** or by using our built-in **Theme Generator**.
320
+
321
+ ### 🛠️ Built-in Theme Generator
322
+
323
+ The easiest way to create a consistent theme is to use our CLI utility. It generates a configuration object that you can pass directly to the component.
324
+
325
+ **1. Run the generator in your terminal:**
326
+
327
+ ```bash
328
+ npx getSignpadTheme
295
329
  ```
296
330
 
297
- #### `downloadSignatureImage(filename?: string, format?: string, quality?: number)`
331
+ The CLI will guide you through:
298
332
 
299
- This method triggers a download of the signature as an image file directly in the browser.
333
+ - **Output path:** Where to save the file.
334
+ - **Filename:** What to call the file.
335
+ - **Format:** Choose between `.js` or `.ts`.
336
+
337
+ **2. Import and apply the theme:**
338
+ Once generated, import the file and pass it to your configuration object:
300
339
 
301
340
  ```typescript
302
- import { SignosoftSignpad } from "@signosoft/signpad-js";
341
+ import { myCustomTheme } from "./styles/myCustomTheme";
303
342
 
304
- const signpadElement = document.querySelector('signosoft-signpad') as SignosoftSignpad;
343
+ this.config = {
344
+ licenseKey: "...",
345
+ customCssVariables: myCustomTheme,
346
+ };
347
+ ```
305
348
 
306
- // ... (after connecting and some drawing has occurred) ...
349
+ ### ✍️ Manual CSS Customization
307
350
 
308
- if (signpadElement) {
309
- // Download as 'my-signature.png' (default)
310
- signpadElement.downloadSignatureImage('my-signature.png');
351
+ You can override the CSS variables directly in your global stylesheet to fine-tune the appearance:
311
352
 
312
- // Download as 'document-signature.jpeg' with 90% quality
313
- signpadElement.downloadSignatureImage('document-signature.jpeg', 'image/jpeg', 0.9);
353
+ ```css
354
+ signosoft-signpad {
355
+ --primary-color-0: #0056b3;
356
+ --sign-canvas-bg-base: #ffffff;
314
357
  }
315
358
  ```
316
359
 
317
- **Note:** The `getSignatureImageBase64` method returns `null` if the canvas is not available or if no drawing has been started (`_hasStartedDrawing` is false). For `downloadSignatureImage`, if no image data is available, a console warning will be logged, and no download will occur.
360
+ ### 📋 Full CSS Variable Reference
318
361
 
319
- ---
362
+ #### Base Colors & General
320
363
 
321
- ## Styling
364
+ | Variable | Default | Description |
365
+ | :---------------------- | :------------------ | :-------------------------- |
366
+ | `--primary-color-0` | `#4e56ea` | Primary brand color. |
367
+ | `--primary-color-10` | `#7178ee` | Primary hover/accent color. |
368
+ | `--background-color-0` | `#f1f2fd` | Secondary background color. |
369
+ | `--background-color-10` | `#e3e4fc` | Main bar background color. |
370
+ | `--text-color-0` | `#333e4a` | Main text color. |
371
+ | `--white-color` | `#ffffff` | Pure white color. |
372
+ | `--grey-color` | `#b5b9be` | Disabled state color. |
373
+ | `--sign-font-family` | `Arial, sans-serif` | Global font family. |
322
374
 
323
- The component can be styled using standard CSS and by overriding custom CSS variables on the host element (`<signosoft-signpad>`) or through the `customCssVariables` property.
375
+ #### Layout & Constraints
324
376
 
325
- Example of custom CSS variables (check `signosoft-signpad.css` for a full list of available variables):
377
+ | Variable | Default | Description |
378
+ | :---------------------- | :---------- | :------------------------------------- |
379
+ | `--min-height` | `48px` | Minimum height for bars and buttons. |
380
+ | `--spacing-constraints` | `16px 24px` | Default padding/margin for containers. |
326
381
 
327
- ```css
328
- export const myCustomSignpadTheme = {
329
- // Font
330
- "--sign-font-family": "Arial, Helvetica, sans-serif",
331
- // Top Bar
332
- "--sign-top-bar-bg-base": "#e3e4fc",
333
- "--sign-top-bar-text-base": "#4e56ea",
334
-
335
- // Canvas Area
336
- "--sign-canvas-bg-base": "#f1f2fd",
337
-
338
- // Line
339
- "--sign-line-height-base": "22px",
340
- "--sign-line-border-base": "#7178ee",
341
- "--sign-line-additional-text-color": "#333E4A",
342
-
343
- // Bottom Bar
344
- "--sign-bottom-bar-bg-base": "#e3e4fc",
345
-
346
- // Primary Buttons (OK, Clear, Cancel)
347
- "--sign-button-primary-bg-base": "#4e56ea",
348
- "--sign-button-primary-bg-hover": "#7178ee",
349
- "--sign-button-primary-bg-disabled": "#b5b9be",
350
- "--sign-button-primary-text-base": "#ffffff",
351
- "--sign-button-primary-text-hover": "#ffffff",
352
- "--sign-button-primary-text-disabled": "white",
353
-
354
- // Link Buttons (Connect signpad)
355
- "--sign-button-link-bg-base": "transparent",
356
- "--sign-button-link-bg-hover": "#e3e4fc",
357
- "--sign-button-link-bg-disabled": "transparent",
358
- "--sign-button-link-text-base": "#4e56ea",
359
- "--sign-button-link-text-hover": "#7178ee",
360
- "--sign-button-link-text-disabled": "#b5b9be",
361
- "--sign-button-link-border-base": "1px solid #4e56ea",
362
- "--sign-button-link-border-hover": "1px solid #7178ee",
363
- "--sign-button-link-border-disabled": "1px solid #b5b9be",
364
-
365
- // Device State Text Colors
366
- "--sign-device-state-text-color-connected": "green",
367
- "--sign-device-state-text-color-disconnected": "red",
368
-
369
- // Loading Overlay
370
- "--sign-loading-overlay-bg-color": "rgba(255, 255, 255, 0.8);",
371
- "--sign-loading-overlay-text-color": "#333e4a",
372
- "--sign-loading-overlay-spinner-color": "#4e56ea",
373
- "--sign-loading-overlay-spinner-border-color": "rgba(78, 86, 234, 0.1)",
374
- "--sign-loading-overlay-spinner-size": "30px",
375
- };
376
- ```
382
+ #### Top Bar
383
+
384
+ | Variable | Description |
385
+ | :-------------------------- | :------------------------------- |
386
+ | `--sign-top-bar-bg-base` | Background color of the top bar. |
387
+ | `--sign-top-bar-text-base` | Text color in the top bar. |
388
+ | `--sign-top-bar-padding` | Inner padding of the top bar. |
389
+ | `--sign-top-bar-min-height` | Minimum height of the top bar. |
390
+
391
+ #### Canvas & Signature Line
392
+
393
+ | Variable | Description |
394
+ | :---------------------------------- | :-------------------------------------------- |
395
+ | `--sign-canvas-bg-base` | Background color of the drawing area. |
396
+ | `--sign-line-height` | Vertical offset/height for the guide line. |
397
+ | `--sign-line-border-base` | Color of the signature guide line. |
398
+ | `--sign-line-additional-text-color` | Color of the helper text below the line. |
399
+ | `--sign-line-margin` | Spacing around the guide line. |
400
+ | `--sign-canvas-line-text-font-size` | Font size for guide line labels. |
401
+ | `--sign-canvas-height-offset` | Canvas offset calculation for the guide line. |
402
+
403
+ #### Bottom Bar
404
+
405
+ | Variable | Description |
406
+ | :----------------------------- | :--------------------------------------- |
407
+ | `--sign-bottom-bar-bg-base` | Background color of the bottom bar. |
408
+ | `--sign-bottom-bar-padding` | Inner padding of the bottom bar. |
409
+ | `--sign-bottom-bar-min-height` | Minimum height of the bottom bar. |
410
+ | `--sign-bottom-bar-gap` | Space between buttons in the bottom bar. |
411
+
412
+ #### Buttons (General)
413
+
414
+ | Variable | Default | Description |
415
+ | :------------------------- | :------------ | :------------------------------- |
416
+ | `--sign-button-font-size` | `12px - 16px` | Fluid font size for all buttons. |
417
+ | `--sign-button-padding` | `14px 16px` | Inner padding for all buttons. |
418
+ | `--sign-button-min-height` | `48px` | Minimum height for buttons. |
419
+
420
+ #### Primary Buttons (OK, Clear, Cancel)
421
+
422
+ | Variable | Description |
423
+ | :------------------------------------ | :----------------------------------- |
424
+ | `--sign-button-primary-bg-base` | Background color of primary buttons. |
425
+ | `--sign-button-primary-bg-hover` | Hover background color. |
426
+ | `--sign-button-primary-bg-disabled` | Disabled background color. |
427
+ | `--sign-button-primary-text-base` | Text color for primary buttons. |
428
+ | `--sign-button-primary-text-hover` | Hover text color. |
429
+ | `--sign-button-primary-text-disabled` | Disabled text color. |
430
+
431
+ #### Link/Connect Buttons
432
+
433
+ | Variable | Description |
434
+ | :-------------------------------- | :------------------------------------------- |
435
+ | `--sign-button-link-bg-base` | Background color for secondary/link buttons. |
436
+ | `--sign-button-link-text-base` | Text color for secondary/link buttons. |
437
+ | `--sign-button-link-border-base` | Border for secondary/link buttons. |
438
+ | `--sign-button-link-text-hover` | Hover text color. |
439
+ | `--sign-button-link-border-hover` | Hover border color. |
440
+
441
+ #### Status & Overlays
442
+
443
+ | Variable | Default | Description |
444
+ | :-------------------------------------------- | :---------- | :--------------------------------- |
445
+ | `--sign-device-state-text-color-connected` | `green` | Text color when device is ready. |
446
+ | `--sign-device-state-text-color-disconnected` | `red` | Text color when disconnected. |
447
+ | `--sign-loading-overlay-bg-color` | `rgba(...)` | Background of the loading spinner. |
448
+ | `--sign-loading-overlay-spinner-color` | `#4e56ea` | Color of the animated spinner. |
449
+ | `--sign-loading-overlay-spinner-size` | `30px` | Size of the spinner icon. |
450
+
451
+ ## 🤝 Feedback & Support
452
+
453
+ We are constantly working to improve our components and drivers. Your feedback is essential to us. Whether you found a bug, have a feature request, or need technical assistance, please reach out to us:
454
+
455
+ - 📧 **Support Email:** [esign@signosoft.com](mailto:esign@signosoft.com)
456
+ - 🌐 **Official Website:** [www.signosoft.com](https://www.signosoft.com)
457
+
458
+ ## 📄 License
459
+
460
+ **Proprietary Commercial License**
461
+
462
+ Copyright © 2026, Signosoft. All rights reserved.
463
+
464
+ This software is proprietary to Signosoft and is protected by copyright laws. It is **not open source**.
465
+
466
+ ### 🔐 Commercial Usage
467
+
468
+ A valid, paid, and active commercial license agreement with Signosoft is **strictly required** for the use, operation, reproduction, distribution, or deployment of this software in any environment (including development, testing, staging, and production).
469
+
470
+ ### 📜 Key Terms
471
+
472
+ - **Unauthorized Use:** Any use without a current, fully paid license is expressly prohibited and constitutes a violation of our intellectual property rights.
473
+ - **Legal Action:** Signosoft reserves the right to pursue legal action to enforce its rights and seek damages for unauthorized use.
474
+ - **Restrictions:** You may not reverse-engineer, decompile, or disassemble this software except as permitted by applicable law.
475
+
476
+ For information on how to obtain a valid commercial license, pricing, and support, please contact us at [esign@signosoft.com](mailto:esign@signosoft.com).
477
+
478
+ See the [LICENSE](LICENSE) file for the full legal text.