@mkhuda/dom-screenshot 0.0.2 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.gitattributes +1 -0
  2. package/EXAMPLES_QUICKSTART.md +240 -0
  3. package/README.md +534 -33
  4. package/TESTING.md +269 -0
  5. package/TESTING_STATUS.md +215 -0
  6. package/TEST_SETUP_SUMMARY.md +335 -0
  7. package/dist/dom-screenshot.d.ts +44 -272
  8. package/dist/dom-screenshot.d.ts.map +1 -0
  9. package/dist/dom-screenshot.esm.js +753 -0
  10. package/dist/dom-screenshot.esm.js.map +1 -0
  11. package/dist/dom-screenshot.min.js +2 -1
  12. package/dist/dom-screenshot.min.js.map +1 -0
  13. package/examples/README.md +211 -0
  14. package/examples/react-app/README.md +161 -0
  15. package/examples/react-app/index.html +12 -0
  16. package/examples/react-app/node_modules/.vite/deps/_metadata.json +46 -0
  17. package/examples/react-app/node_modules/.vite/deps/chunk-FK77NBP6.js +1895 -0
  18. package/examples/react-app/node_modules/.vite/deps/chunk-FK77NBP6.js.map +7 -0
  19. package/examples/react-app/node_modules/.vite/deps/chunk-VSODSHUF.js +21647 -0
  20. package/examples/react-app/node_modules/.vite/deps/chunk-VSODSHUF.js.map +7 -0
  21. package/examples/react-app/node_modules/.vite/deps/package.json +3 -0
  22. package/examples/react-app/node_modules/.vite/deps/react-dom.js +5 -0
  23. package/examples/react-app/node_modules/.vite/deps/react-dom.js.map +7 -0
  24. package/examples/react-app/node_modules/.vite/deps/react-dom_client.js +38 -0
  25. package/examples/react-app/node_modules/.vite/deps/react-dom_client.js.map +7 -0
  26. package/examples/react-app/node_modules/.vite/deps/react.js +4 -0
  27. package/examples/react-app/node_modules/.vite/deps/react.js.map +7 -0
  28. package/examples/react-app/node_modules/.vite/deps/react_jsx-dev-runtime.js +898 -0
  29. package/examples/react-app/node_modules/.vite/deps/react_jsx-dev-runtime.js.map +7 -0
  30. package/examples/react-app/node_modules/.vite/deps/react_jsx-runtime.js +910 -0
  31. package/examples/react-app/node_modules/.vite/deps/react_jsx-runtime.js.map +7 -0
  32. package/examples/react-app/package.json +21 -0
  33. package/examples/react-app/tsconfig.json +25 -0
  34. package/examples/react-app/tsconfig.node.json +10 -0
  35. package/examples/react-app/vite.config.ts +10 -0
  36. package/package.json +75 -43
  37. package/rollup.config.mjs +35 -0
  38. package/tests/README.md +394 -0
  39. package/tests/fixtures/html.ts +192 -0
  40. package/tests/fixtures/images.ts +86 -0
  41. package/tests/fixtures/styles.ts +288 -0
  42. package/tests/helpers/dom-helpers.ts +242 -0
  43. package/tests/mocks/canvas-mock.ts +94 -0
  44. package/tests/mocks/image-mock.ts +147 -0
  45. package/tests/mocks/xhr-mock.ts +202 -0
  46. package/tests/setup.ts +103 -0
  47. package/tests/unit/basic.test.ts +263 -0
  48. package/tests/unit/simple.test.ts +172 -0
  49. package/tsconfig.json +44 -20
  50. package/vitest.config.mts +35 -0
  51. package/rollup.config.js +0 -20
package/README.md CHANGED
@@ -1,53 +1,554 @@
1
1
  # dom-screenshot
2
+
2
3
  [![Build Status](https://app.travis-ci.com/mkhuda/dom-screenshot.svg?branch=main)](https://app.travis-ci.com/mkhuda/dom-screenshot) [![npm version](https://badge.fury.io/js/%40mkhuda%2Fdom-screenshot.svg)](https://badge.fury.io/js/%40mkhuda%2Fdom-screenshot)
3
4
 
4
- DOM screenshot by dom-to-image forked & modified from [dom-to-image](https://github.com/tsayen/dom-to-image)
5
+ A modern TypeScript library to capture DOM elements as **SVG**, **PNG**, **JPEG**, or **Blob** images. Built with latest tooling and fully type-safe.
6
+
7
+ > Forked & modified from [dom-to-image](https://github.com/tsayen/dom-to-image)
8
+
9
+ ---
10
+
11
+ ## ✨ Features
12
+
13
+ - 📸 **Multiple Formats**: SVG (vector), PNG (raster), JPEG (compressed), Blob, Pixel Data
14
+ - 🎨 **Style Preservation**: Captures all CSS styles, colors, gradients, shadows, transforms
15
+ - 📦 **Modern Build**: Rollup with TypeScript, ESM and CommonJS outputs
16
+ - 🔒 **Type Safe**: Full TypeScript support with complete type definitions
17
+ - ⚡ **Fast**: Optimized for performance, lazy initialization of dependencies
18
+ - 🚀 **Production Ready**: Tested and used in real-world applications
19
+ - 🎯 **React Friendly**: Works seamlessly with React via refs
20
+
21
+ ---
22
+
23
+ ## 📚 Documentation
24
+
25
+ ### Quick Reference
26
+ - **Getting Started** → See below or check [`EXAMPLES_QUICKSTART.md`](./EXAMPLES_QUICKSTART.md)
27
+ - **React Example** → Run the interactive example in `examples/react-app/`
28
+ - **Testing** → See [`TESTING.md`](./TESTING.md) for test setup
29
+ - **Examples** → Check [`examples/README.md`](./examples/README.md) for detailed examples
30
+
31
+ ### File Guides
32
+
33
+ | File | Purpose |
34
+ |------|---------|
35
+ | `EXAMPLES_QUICKSTART.md` | Quick start guide for running examples |
36
+ | `TESTING.md` | Testing framework setup and usage |
37
+ | `TESTING_STATUS.md` | Current test status and results |
38
+ | `TEST_SETUP_SUMMARY.md` | Comprehensive testing documentation |
39
+ | `examples/README.md` | Examples overview |
40
+ | `examples/react-app/README.md` | Detailed React example guide |
41
+ | `tests/README.md` | Test infrastructure details |
42
+
43
+ ---
44
+
45
+ ## 🚀 Quick Start
46
+
47
+ ### Installation
5
48
 
6
- ## Install
7
49
  ```bash
8
- # YARN
9
- yarn add @mkhuda/dom-screenshot
10
- # NPM
11
50
  npm install @mkhuda/dom-screenshot
51
+ # or
52
+ yarn add @mkhuda/dom-screenshot
53
+ ```
54
+
55
+ ### Basic Usage
56
+
57
+ ```typescript
58
+ import { domtoimage } from '@mkhuda/dom-screenshot';
59
+
60
+ // Get the element to capture
61
+ const element = document.getElementById('content');
62
+
63
+ // Capture as SVG
64
+ const svg = await domtoimage.toSvg(element);
65
+
66
+ // Capture as PNG
67
+ const png = await domtoimage.toPng(element);
68
+
69
+ // Capture as JPEG
70
+ const jpeg = await domtoimage.toJpeg(element);
71
+
72
+ // Get as Blob
73
+ const blob = await domtoimage.toBlob(element);
74
+
75
+ // Get pixel data
76
+ const pixelData = await domtoimage.toPixelData(element);
77
+ ```
78
+
79
+ ### React Example
80
+
81
+ ```typescript
82
+ import { useRef } from 'react';
83
+ import { domtoimage } from '@mkhuda/dom-screenshot';
84
+
85
+ export function MyComponent() {
86
+ const contentRef = useRef<HTMLDivElement>(null);
87
+
88
+ const handleCapture = async () => {
89
+ if (!contentRef.current) return;
90
+
91
+ try {
92
+ const png = await domtoimage.toPng(contentRef.current);
93
+
94
+ // Download
95
+ const link = document.createElement('a');
96
+ link.href = png;
97
+ link.download = 'screenshot.png';
98
+ link.click();
99
+ } catch (error) {
100
+ console.error('Capture failed:', error);
101
+ }
102
+ };
103
+
104
+ return (
105
+ <div>
106
+ <div ref={contentRef}>
107
+ <h1>Content to capture</h1>
108
+ <p>This will be captured</p>
109
+ </div>
110
+ <button onClick={handleCapture}>📸 Download as PNG</button>
111
+ </div>
112
+ );
113
+ }
114
+ ```
115
+
116
+ ---
117
+
118
+ ## 📸 API Reference
119
+
120
+ ### Functions
121
+
122
+ #### `toSvg(node, options?)`
123
+ Renders DOM node to SVG data URL (scalable vector format).
124
+
125
+ **Returns:** `Promise<string>` - SVG data URL
126
+
127
+ **Best for:** UI components, diagrams, simple graphics
128
+
129
+ ```typescript
130
+ const svg = await domtoimage.toSvg(element);
131
+ ```
132
+
133
+ #### `toPng(node, options?)`
134
+ Renders DOM node to PNG data URL (lossless raster format).
135
+
136
+ **Returns:** `Promise<string>` - PNG data URL
137
+
138
+ **Best for:** Screenshots, general purpose captures
139
+
140
+ ```typescript
141
+ const png = await domtoimage.toPng(element);
142
+ ```
143
+
144
+ #### `toJpeg(node, options?)`
145
+ Renders DOM node to JPEG data URL (lossy compressed format).
146
+
147
+ **Returns:** `Promise<string>` - JPEG data URL
148
+
149
+ **Best for:** Photos, space-constrained scenarios
150
+
151
+ ```typescript
152
+ const jpeg = await domtoimage.toJpeg(element, { quality: 0.95 });
153
+ ```
154
+
155
+ #### `toBlob(node, options?)`
156
+ Renders DOM node to Blob object.
157
+
158
+ **Returns:** `Promise<Blob>` - Blob object
159
+
160
+ **Best for:** Uploading to server, efficient data handling
161
+
162
+ ```typescript
163
+ const blob = await domtoimage.toBlob(element);
164
+ ```
165
+
166
+ #### `toPixelData(node, options?)`
167
+ Extracts raw pixel data from DOM node.
168
+
169
+ **Returns:** `Promise<Uint8ClampedArray>` - RGBA pixel data
170
+
171
+ **Best for:** Image processing, pixel manipulation
172
+
173
+ ```typescript
174
+ const pixelData = await domtoimage.toPixelData(element);
175
+ ```
176
+
177
+ ### Options
178
+
179
+ ```typescript
180
+ interface DomScreenshotOptions {
181
+ width?: number; // Override width
182
+ height?: number; // Override height
183
+ bgcolor?: string; // Background color
184
+ quality?: number; // JPEG quality (0-1)
185
+ style?: CSSStyleDeclaration; // Additional styles
186
+ filter?: (node: Node) => boolean; // Filter nodes
187
+ cacheBust?: boolean; // Bust cache with random query
188
+ imagePlaceholder?: string; // Placeholder for broken images
189
+ }
190
+ ```
191
+
192
+ ---
193
+
194
+ ## 🎯 Real-World Use Cases
195
+
196
+ ### 1. Export Feature
197
+ Let users download rendered UI as images:
198
+ ```typescript
199
+ const png = await domtoimage.toPng(contentElement);
200
+ downloadFile(png, 'export.png');
201
+ ```
202
+
203
+ ### 2. Report Generation
204
+ Create visual reports from data:
205
+ ```typescript
206
+ const reports = await Promise.all([
207
+ domtoimage.toPng(chart1),
208
+ domtoimage.toPng(chart2),
209
+ domtoimage.toPng(table),
210
+ ]);
211
+ ```
212
+
213
+ ### 3. Screenshot Tools
214
+ Build screenshot applications:
215
+ ```typescript
216
+ const screenshots = [];
217
+ screenshots.push(await domtoimage.toPng(screen1));
218
+ screenshots.push(await domtoimage.toPng(screen2));
219
+ ```
220
+
221
+ ### 4. Documentation
222
+ Auto-capture UI for documentation:
223
+ ```typescript
224
+ const componentScreenshot = await domtoimage.toSvg(component);
225
+ ```
226
+
227
+ ---
228
+
229
+ ## 🧪 Testing
230
+
231
+ The project includes a comprehensive test suite with:
232
+
233
+ - ✅ 20 infrastructure tests
234
+ - ✅ Unit tests for all functions
235
+ - ✅ Integration tests
236
+ - ✅ Custom test matchers
237
+ - ✅ Full TypeScript support
238
+
239
+ ### Run Tests
240
+
241
+ ```bash
242
+ # Run tests once
243
+ npm run test:run
244
+
245
+ # Watch mode
246
+ npm run test:watch
247
+
248
+ # UI dashboard
249
+ npm run test:ui
250
+
251
+ # Coverage report
252
+ npm run test:coverage
253
+ ```
254
+
255
+ See [`TESTING.md`](./TESTING.md) for detailed testing information.
256
+
257
+ ---
258
+
259
+ ## 💻 Examples
260
+
261
+ ### React Example App
262
+
263
+ A complete, production-ready React application demonstrating all features:
264
+
265
+ **Features:**
266
+ - Capture as SVG, PNG, JPEG
267
+ - Live preview gallery
268
+ - Auto-download files
269
+ - Beautiful responsive UI
270
+ - Full TypeScript
271
+
272
+ **Quick Start:**
273
+ ```bash
274
+ npm run example:dev
275
+ ```
276
+
277
+ Opens at `http://localhost:5173`
278
+
279
+ For detailed information, see:
280
+ - [`EXAMPLES_QUICKSTART.md`](./EXAMPLES_QUICKSTART.md) - Quick reference
281
+ - [`examples/README.md`](./examples/README.md) - Examples overview
282
+ - [`examples/react-app/README.md`](./examples/react-app/README.md) - Detailed guide
283
+
284
+ ---
285
+
286
+ ## 🏗️ Project Structure
287
+
288
+ ```
289
+ dom-screenshot/
290
+ ├── src/
291
+ │ ├── dom-screenshot.ts # Main library
292
+ │ └── types/
293
+ │ └── options.ts # Type definitions
294
+ ├── dist/
295
+ │ ├── dom-screenshot.esm.js # ES Module
296
+ │ ├── dom-screenshot.min.js # IIFE (minified)
297
+ │ └── dom-screenshot.d.ts # TypeScript types
298
+ ├── tests/
299
+ │ ├── setup.ts # Test configuration
300
+ │ ├── helpers/ # Test utilities
301
+ │ ├── mocks/ # Mock implementations
302
+ │ ├── fixtures/ # Test data
303
+ │ └── unit/
304
+ │ ├── simple.test.ts # Infrastructure tests
305
+ │ └── basic.test.ts # Feature tests
306
+ ├── examples/
307
+ │ └── react-app/ # React example application
308
+ ├── vitest.config.mts # Test runner config
309
+ ├── tsconfig.json # TypeScript config
310
+ ├── rollup.config.mjs # Build config
311
+ └── package.json
312
+ ```
313
+
314
+ ---
315
+
316
+ ## 🛠️ Development
317
+
318
+ ### Prerequisites
319
+ - Node.js 22.12.0 (pinned with Volta)
320
+ - npm or yarn
321
+
322
+ ### Setup
323
+
324
+ ```bash
325
+ # Install dependencies
326
+ npm install
327
+
328
+ # Build library
329
+ npm run build
330
+
331
+ # Watch for changes
332
+ npm run watch
333
+ ```
334
+
335
+ ### Build Commands
336
+
337
+ ```bash
338
+ npm run build # Build production
339
+ npm run test:run # Run tests
340
+ npm run test:watch # Watch tests
341
+ npm run test:ui # Test UI dashboard
342
+ npm run example:dev # Run React example
343
+ npm run example:build # Build React example
344
+ ```
345
+
346
+ ---
347
+
348
+ ## 📊 What's New (TypeScript Migration)
349
+
350
+ ### ✅ Completed
351
+
352
+ - ✅ Full TypeScript migration
353
+ - ✅ Strict type checking enabled
354
+ - ✅ Modern build tooling (Rollup 4.x, TypeScript 5.x)
355
+ - ✅ ESM and CommonJS dual output
356
+ - ✅ Complete test suite (20+ tests passing)
357
+ - ✅ Production-ready React example
358
+ - ✅ Comprehensive documentation
359
+
360
+ ### 🎯 Quality Metrics
361
+
362
+ | Metric | Status |
363
+ |--------|--------|
364
+ | TypeScript | ✅ Full coverage with strict mode |
365
+ | Tests | ✅ 20+ tests passing |
366
+ | Build | ✅ 0 errors |
367
+ | Output | ✅ ESM + IIFE dual format |
368
+ | Types | ✅ Complete definitions |
369
+ | Docs | ✅ Comprehensive guides |
370
+
371
+ ---
372
+
373
+ ## 🚀 Browser Support
374
+
375
+ - ✅ Chrome/Chromium (latest)
376
+ - ✅ Firefox (latest)
377
+ - ✅ Safari (latest)
378
+ - ✅ Edge (latest)
379
+
380
+ For older browsers, ensure required polyfills are present.
381
+
382
+ ---
383
+
384
+ ## 🔄 Format Comparison
385
+
386
+ | Format | Use Case | Size | Speed | Quality |
387
+ |--------|----------|------|-------|---------|
388
+ | **SVG** | UI/Diagrams | Smallest | Fastest | Vector |
389
+ | **PNG** | General Purpose | Medium | Medium | Lossless |
390
+ | **JPEG** | Photos | Smallest | Slower | Lossy |
391
+ | **Blob** | Server Upload | Any | Any | Any |
392
+
393
+ ---
394
+
395
+ ## ⚙️ Advanced Options
396
+
397
+ ### Custom Dimensions
398
+
399
+ ```typescript
400
+ const png = await domtoimage.toPng(element, {
401
+ width: 1920,
402
+ height: 1080,
403
+ });
12
404
  ```
13
405
 
406
+ ### Background Color
14
407
 
15
- ## Added & Fix:
16
- - Change to rollup build
17
- - Add encodeURIComponent on makeSvgDataUri. Based on [this](https://github.com/tsayen/dom-to-image/issues/78) issue
18
- - Add Typescript support, (.d.ts) battery included.
408
+ ```typescript
409
+ const png = await domtoimage.toPng(element, {
410
+ bgcolor: '#ffffff',
411
+ });
412
+ ```
19
413
 
20
- ## TODO (on progress):
21
- - Full rewrite to Typescript
22
- - Adding `chai` test (on progress).
414
+ ### JPEG Quality
23
415
 
24
- ## Usages (React)
25
416
  ```typescript
26
- import DomScreenshot from "@mkhuda/dom-screenshot";
27
- ....
417
+ const jpeg = await domtoimage.toJpeg(element, {
418
+ quality: 0.95, // 0 to 1
419
+ });
420
+ ```
28
421
 
29
- return(
30
- <button
31
- onClick={() => {
32
- const getElement = document.getElementById("root") as HTMLElement;
33
- const image = DomScreenshot.toPng(document.body, {});
34
- image.then((generatedImage) => {
35
- window.open(generatedImage);
36
- });
37
- }}
38
- >
39
- Test
40
- </button>
41
- )
42
- ...
422
+ ### Filter Nodes
423
+
424
+ ```typescript
425
+ const svg = await domtoimage.toSvg(element, {
426
+ filter: (node) => {
427
+ // Exclude elements with class 'no-capture'
428
+ if (node instanceof HTMLElement) {
429
+ return !node.classList.contains('no-capture');
430
+ }
431
+ return true;
432
+ },
433
+ });
434
+ ```
435
+
436
+ ### Cache Busting
437
+
438
+ ```typescript
439
+ const png = await domtoimage.toPng(element, {
440
+ cacheBust: true, // Add random query string to URLs
441
+ });
43
442
  ```
44
443
 
45
- ## Contributing
444
+ ---
445
+
446
+ ## 🐛 Troubleshooting
447
+
448
+ ### Styles Not Captured
449
+ - Ensure styles are inline or in `<style>` tags
450
+ - External stylesheets may not be included
451
+ - Use computed styles for debugging
452
+
453
+ ### Canvas-Related Errors
454
+ - SVG capture works in all environments
455
+ - PNG/JPEG may need browser environment
456
+ - Always use try-catch blocks
457
+
458
+ ### Performance Issues
459
+ - Use SVG for simple UI elements
460
+ - Break large captures into sections
461
+ - Cache element references
462
+
463
+ ### Import Errors
464
+ - Ensure library is built: `npm run build`
465
+ - Check Node.js version: `node --version`
466
+ - Try reinstalling: `rm -rf node_modules && npm install`
46
467
 
47
- Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
468
+ ---
48
469
 
49
- Please make sure to update tests as appropriate.
470
+ ## 📄 File Guides
50
471
 
51
- ## License
472
+ ### Main Documentation Files
473
+
474
+ #### `TESTING.md`
475
+ Quick reference for:
476
+ - Running tests
477
+ - Test commands
478
+ - Test patterns
479
+
480
+ #### `TESTING_STATUS.md`
481
+ Current test status:
482
+ - Test results
483
+ - Coverage information
484
+ - Known issues
485
+
486
+ #### `TEST_SETUP_SUMMARY.md`
487
+ Comprehensive testing:
488
+ - Setup details
489
+ - Infrastructure overview
490
+ - Test organization
491
+
492
+ #### `EXAMPLES_QUICKSTART.md`
493
+ Quick start for examples:
494
+ - Installation steps
495
+ - Running instructions
496
+ - Troubleshooting
497
+
498
+ #### `examples/README.md`
499
+ Examples overview:
500
+ - Available examples
501
+ - Features demonstrated
502
+ - Technologies used
503
+
504
+ #### `examples/react-app/README.md`
505
+ React example details:
506
+ - Project structure
507
+ - Component documentation
508
+ - Customization guide
509
+
510
+ #### `tests/README.md`
511
+ Testing infrastructure:
512
+ - Test setup
513
+ - Helper utilities
514
+ - Mock implementations
515
+
516
+ ---
517
+
518
+ ## 🤝 Contributing
519
+
520
+ Contributions are welcome! Please:
521
+
522
+ 1. Fork the repository
523
+ 2. Create a feature branch
524
+ 3. Add tests for new features
525
+ 4. Ensure all tests pass
526
+ 5. Submit a pull request
527
+
528
+ See `TESTING.md` for test setup instructions.
529
+
530
+ ---
531
+
532
+ ## 📝 License
52
533
 
53
534
  [MIT](https://choosealicense.com/licenses/mit/)
535
+
536
+ ---
537
+
538
+ ## 🙏 Acknowledgments
539
+
540
+ - Original library: [dom-to-image](https://github.com/tsayen/dom-to-image) by tsayen
541
+ - Modern tooling and TypeScript migration by Muhammad K. Huda
542
+
543
+ ---
544
+
545
+ ## 📞 Support
546
+
547
+ - 📖 Check the documentation files listed above
548
+ - 🐛 Found a bug? [Open an issue](https://github.com/mkhuda/dom-screenshot/issues)
549
+ - 💬 Have questions? Check existing issues or discussions
550
+ - 🚀 Want to contribute? See Contributing section
551
+
552
+ ---
553
+
554
+ **Ready to capture? Start with the [React example](#-examples) or read the [Quick Start](#-quick-start)!** 📸