@paperpic/vue 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,196 @@
1
+ ---
2
+ title: Attach and scan
3
+ description: A complete example where the user takes a photo of a document or picks a file, straightens and cleans it up in PaperPic, and sends the result to your server, in plain JavaScript, Vue and React.
4
+ ---
5
+
6
+ # Attach and scan
7
+
8
+ Most apps that take documents ask the user for a photo of one, such as a receipt for an expense or a signed form. This example lets the user take the photo or pick a file, edit it in PaperPic, and send the result to your server.
9
+
10
+ `upload` is the function from [Upload to a server](./upload), which sends the image and fails when the server does not accept it.
11
+
12
+ :::tabs key:framework
13
+ == JavaScript
14
+
15
+ ```html
16
+ <label>
17
+ Photo of the document
18
+ <input id="photo" type="file" accept="image/*" capture="environment" />
19
+ </label>
20
+ <div id="viewer" style="height: 480px"></div>
21
+ <p id="status" role="status"></p>
22
+ ```
23
+
24
+ ```ts
25
+ import { PaperPic } from '@paperpic/core'
26
+ import '@paperpic/core/style.css'
27
+
28
+ const input = document.querySelector<HTMLInputElement>('#photo')!
29
+ const status = document.querySelector('#status')!
30
+
31
+ const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
32
+ alt: 'The document you attached',
33
+ maxOutputSize: 3000,
34
+ })
35
+
36
+ input.addEventListener('change', () => {
37
+ const file = input.files?.[0]
38
+ if (file) {
39
+ status.textContent = ''
40
+ pic.setOptions({ src: file })
41
+ }
42
+ })
43
+
44
+ // The edit starts as soon as the photo is on display
45
+ pic.on('load', () => pic.edit())
46
+
47
+ pic.on('error', ({ phase }) => {
48
+ if (phase === 'load') {
49
+ status.textContent = 'This file is not an image the browser can open'
50
+ }
51
+ })
52
+
53
+ pic.on('apply', async ({ blob, type }) => {
54
+ status.textContent = 'Sending…'
55
+ try {
56
+ await upload(blob, type)
57
+ status.textContent = 'Sent'
58
+ }
59
+ catch {
60
+ status.textContent = 'The document could not be sent'
61
+ }
62
+ })
63
+ ```
64
+
65
+ == Vue
66
+
67
+ ```vue
68
+ <script setup lang="ts">
69
+ import type { ExportedImage, PaperPicEvents } from '@paperpic/vue'
70
+ import { PaperPic } from '@paperpic/vue'
71
+ import { shallowRef, useTemplateRef } from 'vue'
72
+ import '@paperpic/vue/style.css'
73
+
74
+ const pic = useTemplateRef('pic')
75
+ const photo = shallowRef<File>()
76
+ const status = shallowRef('')
77
+
78
+ function choose(event: Event) {
79
+ const file = (event.target as HTMLInputElement).files?.[0]
80
+ if (file) {
81
+ status.value = ''
82
+ photo.value = file
83
+ }
84
+ }
85
+
86
+ function failed({ phase }: PaperPicEvents['error']) {
87
+ if (phase === 'load') {
88
+ status.value = 'This file is not an image the browser can open'
89
+ }
90
+ }
91
+
92
+ async function send({ blob, type }: ExportedImage) {
93
+ status.value = 'Sending…'
94
+ try {
95
+ await upload(blob, type)
96
+ status.value = 'Sent'
97
+ }
98
+ catch {
99
+ status.value = 'The document could not be sent'
100
+ }
101
+ }
102
+ </script>
103
+
104
+ <template>
105
+ <label>
106
+ Photo of the document
107
+ <input type="file" accept="image/*" capture="environment" @change="choose">
108
+ </label>
109
+ <div v-if="photo" style="height: 480px">
110
+ <PaperPic
111
+ ref="pic"
112
+ :src="photo"
113
+ alt="The document you attached"
114
+ :max-output-size="3000"
115
+ @load="pic?.instance?.edit()"
116
+ @error="failed"
117
+ @apply="send"
118
+ />
119
+ </div>
120
+ <p role="status">
121
+ {{ status }}
122
+ </p>
123
+ </template>
124
+ ```
125
+
126
+ == React
127
+
128
+ ```tsx
129
+ import type { ExportedImage, PaperPicEvents, PaperPicInstance } from '@paperpic/react'
130
+ import { PaperPic } from '@paperpic/react'
131
+ import { useRef, useState } from 'react'
132
+ import '@paperpic/react/style.css'
133
+
134
+ export function AttachDocument() {
135
+ const picRef = useRef<PaperPicInstance>(null)
136
+ const [photo, setPhoto] = useState<File>()
137
+ const [status, setStatus] = useState('')
138
+
139
+ function choose(file: File | undefined) {
140
+ if (file) {
141
+ setStatus('')
142
+ setPhoto(file)
143
+ }
144
+ }
145
+
146
+ function failed({ phase }: PaperPicEvents['error']) {
147
+ if (phase === 'load') {
148
+ setStatus('This file is not an image the browser can open')
149
+ }
150
+ }
151
+
152
+ async function send({ blob, type }: ExportedImage) {
153
+ setStatus('Sending…')
154
+ try {
155
+ await upload(blob, type)
156
+ setStatus('Sent')
157
+ }
158
+ catch {
159
+ setStatus('The document could not be sent')
160
+ }
161
+ }
162
+
163
+ return (
164
+ <>
165
+ <label>
166
+ Photo of the document
167
+ <input type="file" accept="image/*" capture="environment" onChange={event => choose(event.target.files?.[0])} />
168
+ </label>
169
+ {photo && (
170
+ <div style={{ height: 480 }}>
171
+ <PaperPic
172
+ ref={picRef}
173
+ src={photo}
174
+ alt="The document you attached"
175
+ maxOutputSize={3000}
176
+ onLoad={() => picRef.current?.edit()}
177
+ onError={failed}
178
+ onApply={send}
179
+ />
180
+ </div>
181
+ )}
182
+ <p role="status">{status}</p>
183
+ </>
184
+ )
185
+ }
186
+ ```
187
+
188
+ :::
189
+
190
+ ## Notes
191
+
192
+ - `capture="environment"` opens the back camera on phones, and computers ignore it. Without it, phones offer the camera and the photo library, which suits documents the user already has.
193
+ - The viewer opens in the edit mode once the photo loads, so the user goes straight to Straighten or Clean up. Leave out the `load` listener to show the photo first.
194
+ - `phase: 'load'` tells a file the browser cannot open, such as a HEIC photo outside Safari, from a failed edit. [Loading images](../guide/loading#formats) lists the formats.
195
+ - The photo stays in the browser until Apply calls `upload`. PaperPic sends nothing on its own.
196
+ - [`maxOutputSize`](../reference/options#maxoutputsize) keeps the upload small. Phone photos have 12 megapixels or more, and documents stay readable at 3000 pixels on the longest side.
@@ -203,6 +203,189 @@ export function Receipt() {
203
203
 
204
204
  :::
205
205
 
206
+ ## A slider of your own {#slider}
207
+
208
+ A slider of your own for Clean up opens the tool first. Each move then calls `setThreshold()`, which changes what Clean up shows, and `confirmTool()` keeps the last value as one edit. Here Done also applies the result, and Cancel leaves the edit mode, so these controls are the whole interface.
209
+
210
+ :::tabs key:framework
211
+ == JavaScript
212
+
213
+ ```html
214
+ <button id="clean-up" type="button">Clean up</button>
215
+ <div id="ruler" hidden>
216
+ <label>
217
+ Sensitivity
218
+ <input id="sensitivity" type="range" min="0" max="1" step="0.05" />
219
+ </label>
220
+ <button id="done" type="button">Done</button>
221
+ <button id="cancel" type="button">Cancel</button>
222
+ </div>
223
+ <div id="viewer" style="height: 480px"></div>
224
+ ```
225
+
226
+ ```ts
227
+ import { PaperPic } from '@paperpic/core'
228
+ import '@paperpic/core/style.css'
229
+
230
+ const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
231
+ src: '/receipt.jpg',
232
+ alt: 'A receipt',
233
+ toolbar: false,
234
+ })
235
+ const slider = document.querySelector<HTMLInputElement>('#sensitivity')!
236
+
237
+ document.querySelector('#clean-up')!.addEventListener('click', () => {
238
+ pic.edit()
239
+ pic.openTool('threshold')
240
+ })
241
+ slider.addEventListener('input', () => pic.setThreshold({ sensitivity: slider.valueAsNumber }))
242
+ document.querySelector('#done')!.addEventListener('click', () => {
243
+ pic.confirmTool()
244
+ pic.apply()
245
+ })
246
+ document.querySelector('#cancel')!.addEventListener('click', () => {
247
+ pic.cancelTool()
248
+ pic.cancel()
249
+ })
250
+
251
+ pic.on('change', ({ activeTool, threshold }) => {
252
+ const open = activeTool === 'threshold'
253
+ document.querySelector<HTMLElement>('#ruler')!.hidden = !open
254
+ document.querySelector<HTMLElement>('#clean-up')!.hidden = open
255
+ slider.value = String(threshold.sensitivity)
256
+ })
257
+ ```
258
+
259
+ == Vue
260
+
261
+ ```vue
262
+ <script setup lang="ts">
263
+ import type { PaperPicState } from '@paperpic/vue'
264
+ import { PaperPic } from '@paperpic/vue'
265
+ import { computed, shallowRef, useTemplateRef } from 'vue'
266
+ import '@paperpic/vue/style.css'
267
+
268
+ const pic = useTemplateRef<InstanceType<typeof PaperPic>>('pic')
269
+ const viewer = computed(() => pic.value?.instance)
270
+ const state = shallowRef<PaperPicState>()
271
+
272
+ function open() {
273
+ viewer.value?.edit()
274
+ viewer.value?.openTool('threshold')
275
+ }
276
+
277
+ function slide(event: Event) {
278
+ viewer.value?.setThreshold({ sensitivity: (event.target as HTMLInputElement).valueAsNumber })
279
+ }
280
+
281
+ function done() {
282
+ viewer.value?.confirmTool()
283
+ viewer.value?.apply()
284
+ }
285
+
286
+ function cancel() {
287
+ viewer.value?.cancelTool()
288
+ viewer.value?.cancel()
289
+ }
290
+ </script>
291
+
292
+ <template>
293
+ <div v-if="state?.activeTool === 'threshold'">
294
+ <label>
295
+ Sensitivity
296
+ <input type="range" min="0" max="1" step="0.05" :value="state.threshold.sensitivity" @input="slide">
297
+ </label>
298
+ <button type="button" @click="done">
299
+ Done
300
+ </button>
301
+ <button type="button" @click="cancel">
302
+ Cancel
303
+ </button>
304
+ </div>
305
+ <button v-else type="button" :disabled="state?.status !== 'ready'" @click="open">
306
+ Clean up
307
+ </button>
308
+ <div style="height: 480px">
309
+ <PaperPic
310
+ ref="pic"
311
+ src="/receipt.jpg"
312
+ alt="A receipt"
313
+ :toolbar="false"
314
+ @change="next => (state = next)"
315
+ @load="state = viewer?.getState()"
316
+ />
317
+ </div>
318
+ </template>
319
+ ```
320
+
321
+ == React
322
+
323
+ ```tsx
324
+ import type { PaperPicInstance, PaperPicState } from '@paperpic/react'
325
+ import { PaperPic } from '@paperpic/react'
326
+ import { useRef, useState } from 'react'
327
+ import '@paperpic/react/style.css'
328
+
329
+ export function CleanUpRuler() {
330
+ const picRef = useRef<PaperPicInstance>(null)
331
+ const [state, setState] = useState<PaperPicState>()
332
+ const viewer = () => picRef.current!
333
+
334
+ function open() {
335
+ viewer().edit()
336
+ viewer().openTool('threshold')
337
+ }
338
+
339
+ function done() {
340
+ viewer().confirmTool()
341
+ viewer().apply()
342
+ }
343
+
344
+ function cancel() {
345
+ viewer().cancelTool()
346
+ viewer().cancel()
347
+ }
348
+
349
+ return (
350
+ <>
351
+ {state?.activeTool === 'threshold'
352
+ ? (
353
+ <div>
354
+ <label>
355
+ Sensitivity
356
+ <input
357
+ type="range"
358
+ min="0"
359
+ max="1"
360
+ step="0.05"
361
+ value={state.threshold.sensitivity}
362
+ onChange={event => viewer().setThreshold({ sensitivity: event.target.valueAsNumber })}
363
+ />
364
+ </label>
365
+ <button type="button" onClick={done}>Done</button>
366
+ <button type="button" onClick={cancel}>Cancel</button>
367
+ </div>
368
+ )
369
+ : (
370
+ <button type="button" disabled={state?.status !== 'ready'} onClick={open}>Clean up</button>
371
+ )}
372
+ <div style={{ height: 480 }}>
373
+ <PaperPic
374
+ ref={picRef}
375
+ src="/receipt.jpg"
376
+ alt="A receipt"
377
+ toolbar={false}
378
+ onChange={setState}
379
+ onLoad={() => setState(viewer().getState())}
380
+ />
381
+ </div>
382
+ </>
383
+ )
384
+ }
385
+ ```
386
+
387
+ :::
388
+
206
389
  ## Notes
207
390
 
208
391
  - With `toolbar: false`, the built-in edit bar is hidden too, so Crop and Straighten show their handles but no Done button. Your interface confirms them with [`confirmTool()`](../reference/methods#confirmtool), as `Enter` does.
@@ -14,7 +14,7 @@ People read and fix documents with a mouse, a finger, the keyboard or a screen r
14
14
  - **Your own controls, if any.** With `toolbar: false`, the buttons you build replace the built-in ones, and they need their own names and keyboard support.
15
15
  - **A visible focus.** Keep your CSS from hiding the focus outline of the viewer.
16
16
 
17
- ## Keyboard
17
+ ## Keyboard {#keyboard}
18
18
 
19
19
  With the focus on the viewer:
20
20
 
@@ -82,11 +82,11 @@ Apply cannot be interrupted. It blocks the controls and shows a message while it
82
82
 
83
83
  ## What your code receives
84
84
 
85
- | Event | When |
86
- | -------- | ------------------------------------------------------------------- |
87
- | `apply` | When the result is ready, with `{ blob, width, height, type }` |
88
- | `change` | After each action of the user, with the [state](../reference/state) |
89
- | `error` | When Apply fails, or when the image cannot be loaded |
85
+ | Event | When |
86
+ | -------- | -------------------------------------------------------------------------- |
87
+ | `apply` | When the result is ready, with `{ blob, width, height, type }` |
88
+ | `change` | After each action of the user that changes the [state](../reference/state) |
89
+ | `error` | When the image cannot be loaded, or an edit cannot be shown or applied |
90
90
 
91
91
  :::tabs key:framework
92
92
  == JavaScript
@@ -128,13 +128,4 @@ After Apply, passing the same `src` again does nothing, so the result stays on d
128
128
 
129
129
  ## Keyboard
130
130
 
131
- With the focus on the viewer:
132
-
133
- | Key | Action |
134
- | -------------------------- | ------------------------------------------------ |
135
- | `Ctrl+Z` | Undo |
136
- | `Ctrl+Shift+Z` or `Ctrl+Y` | Redo |
137
- | `Enter` | Confirm the open tool, or else apply the changes |
138
- | `Esc` | Close the open tool, or else cancel the changes |
139
-
140
- On macOS, `Cmd` works like `Ctrl`.
131
+ With the focus on the viewer, keys undo, redo, confirm and cancel. [Accessibility](./accessibility#keyboard) lists every key.
@@ -9,31 +9,95 @@ This page takes you from installing PaperPic to showing an image and getting the
9
9
 
10
10
  ## Installation
11
11
 
12
- :::tabs key:framework
12
+ ::::tabs key:framework
13
13
  == JavaScript
14
14
 
15
- ```sh
15
+ ::: code-group
16
+
17
+ ```sh [npm]
18
+ npm install @paperpic/core
19
+ ```
20
+
21
+ ```sh [pnpm]
16
22
  pnpm add @paperpic/core
17
23
  ```
18
24
 
25
+ ```sh [yarn]
26
+ yarn add @paperpic/core
27
+ ```
28
+
29
+ ```sh [bun]
30
+ bun add @paperpic/core
31
+ ```
32
+
33
+ :::
34
+
19
35
  == Vue
20
36
 
21
- ```sh
37
+ ::: code-group
38
+
39
+ ```sh [npm]
40
+ npm install @paperpic/vue
41
+ ```
42
+
43
+ ```sh [pnpm]
22
44
  pnpm add @paperpic/vue
23
45
  ```
24
46
 
47
+ ```sh [yarn]
48
+ yarn add @paperpic/vue
49
+ ```
50
+
51
+ ```sh [bun]
52
+ bun add @paperpic/vue
53
+ ```
54
+
55
+ :::
56
+
25
57
  `@paperpic/vue` requires Vue 3.5 or newer.
26
58
 
27
59
  == React
28
60
 
29
- ```sh
61
+ ::: code-group
62
+
63
+ ```sh [npm]
64
+ npm install @paperpic/react
65
+ ```
66
+
67
+ ```sh [pnpm]
30
68
  pnpm add @paperpic/react
31
69
  ```
32
70
 
33
- `@paperpic/react` requires React 19 or newer.
71
+ ```sh [yarn]
72
+ yarn add @paperpic/react
73
+ ```
74
+
75
+ ```sh [bun]
76
+ bun add @paperpic/react
77
+ ```
34
78
 
35
79
  :::
36
80
 
81
+ `@paperpic/react` requires React 19 or newer.
82
+
83
+ ::::
84
+
85
+ ### Without a bundler {#cdn}
86
+
87
+ The core also loads from a CDN that serves the files of the package as they are, such as jsDelivr. Import `dist/index.js` from a module script, and link `dist/style.css`:
88
+
89
+ ```html
90
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@paperpic/core@0.3/dist/style.css" />
91
+ <div id="viewer" style="height: 480px"></div>
92
+ <script type="module">
93
+ import { PaperPic } from 'https://cdn.jsdelivr.net/npm/@paperpic/core@0.3/dist/index.js'
94
+
95
+ const pic = new PaperPic(document.querySelector('#viewer'), { src: '/receipt.jpg', alt: 'A receipt' })
96
+ </script>
97
+ ```
98
+
99
+ Browsers only start a worker from the origin of the page, so the editing runs on the main thread there: it works, but large photos freeze the page for a moment on Apply. Serve the files from your own origin, or use a bundler, to keep the worker. The Vue and React components need a bundler.
100
+
37
101
  ## Show an image
38
102
 
39
103
  The viewer fills its container, so give the container a height. Import the stylesheet once in your app.
@@ -87,7 +151,7 @@ export function Receipt() {
87
151
 
88
152
  :::
89
153
 
90
- `src` takes a URL from the same origin as your page, or a `File` that the user picks, such as from an `<input type="file">`. `alt` describes the image for screen readers.
154
+ `src` takes a URL from the same origin as your page, or a `File` that the user picks, such as from an `<input type="file">`. `alt` describes the image for screen readers. [Loading images](./loading) covers images from other origins, formats and load errors.
91
155
 
92
156
  ## Get the edited image
93
157
 
@@ -126,19 +190,28 @@ async function upload(blob: Blob) {
126
190
 
127
191
  The `blob` keeps the format of the source, or is PNG when the user cleaned up the document. The [`output`](../reference/options#output) option changes it.
128
192
 
193
+ ## Remove the viewer {#destroy}
194
+
195
+ The Vue and React components create the viewer when they mount and destroy it when they unmount. With the core, call [`destroy()`](../reference/methods#destroy) when you take the viewer out of the page, such as when the route changes:
196
+
197
+ ```ts
198
+ pic.destroy()
199
+ ```
200
+
201
+ It removes the viewer from its container, stops its listeners and its worker, and frees the memory of the image. To show it again, create a new one.
202
+
129
203
  ## Only show the image
130
204
 
131
205
  To show a document that people should not change, turn editing off with `editable: false`. The [Viewer](./viewer) page shows it at work.
132
206
 
133
207
  ## Requirements
134
208
 
135
- - PaperPic works in the browsers of [Baseline Widely Available](https://web.dev/baseline).
136
- - The editing runs in a Web Worker, which bundlers such as Vite and webpack pick up on their own. If the worker cannot start, the editing runs on the main thread: it still works, but the page can freeze for a moment with large images.
137
- - With a Content Security Policy, allow the worker with `worker-src 'self'`, and allow `img-src blob:`, because the viewer shows attached files and results through `blob:` URLs.
138
- - With server-side rendering, such as in Nuxt or Next.js, the Vue and React components render an empty element on the server and create the viewer in the browser. With the core, create the viewer in the browser yourself.
209
+ PaperPic works in the browsers of [Baseline Widely Available](https://web.dev/baseline). [Performance and support](./performance) covers the worker, Content Security Policy, server-side rendering and large photos.
139
210
 
140
211
  ## Next steps
141
212
 
213
+ - [Loading images](./loading): where the image comes from, and which formats open.
142
214
  - [Viewer](./viewer): zoom, fit and read-only use.
143
215
  - [Editing](./editing): the edit mode, the tools, Undo and Apply.
144
216
  - [Options](../reference/options): everything you can configure.
217
+ - [Troubleshooting](./troubleshooting): when the viewer does not look or work as it should.
@@ -0,0 +1,128 @@
1
+ ---
2
+ title: Loading images
3
+ description: How to give PaperPic an image, from a URL, a file the user picks or a Blob you fetch, which formats it opens, and how your code learns that the image loaded or failed.
4
+ ---
5
+
6
+ # Loading images
7
+
8
+ PaperPic shows the image that you pass in `src`. This page covers where that image can come from, which formats open, and how your code learns that the image is ready or that it failed.
9
+
10
+ ## Where the image comes from
11
+
12
+ `src` takes one of three things:
13
+
14
+ - **A URL from the same origin as your page**, such as `/documents/42.jpg`.
15
+ - **A `File`** that the user picks with `<input type="file">`. [Attach and scan](../examples/attach-and-scan) shows the whole flow, from the camera to the upload.
16
+ - **A `Blob`** that your code holds, such as the body of a response.
17
+
18
+ For a `File` or a `Blob`, PaperPic creates the `blob:` URL it needs, and frees it when the image changes or the viewer is destroyed.
19
+
20
+ ## Images from another origin, or behind a login {#fetch}
21
+
22
+ PaperPic reads the pixels of the image to edit it. Browsers only allow that for an image from another origin when it arrives with CORS, which PaperPic does not request. Such an image shows, but the first edit fails with an [`error`](../reference/events#error) that says so.
23
+
24
+ Fetch the image yourself, and pass the `Blob` as `src`. This also covers images behind a login, because your request carries the cookies of the user:
25
+
26
+ ```ts
27
+ async function fetchImage(url: string): Promise<Blob> {
28
+ const response = await fetch(url, { credentials: 'include' })
29
+ if (!response.ok) {
30
+ throw new Error(`The image could not be fetched: status ${response.status}`)
31
+ }
32
+ return response.blob()
33
+ }
34
+ ```
35
+
36
+ The other server must allow your origin with CORS, as for any `fetch` from the page.
37
+
38
+ ## Formats {#formats}
39
+
40
+ PaperPic opens every format that the browser shows in an `<img>`:
41
+
42
+ - **JPEG, PNG, WebP and AVIF** open in every [supported browser](./performance#browser-support).
43
+ - **SVG** opens when the file has `width` and `height` attributes. Without them, it has no size, and the load fails.
44
+ - **HEIC**, the format of iPhone photos, only opens in Safari. When an iPhone user picks a photo with `<input type="file" accept="image/*">`, iOS usually hands the page a JPEG copy. A HEIC file that reaches another browser in another way fails to load.
45
+
46
+ Phones often save a photo sideways, with an EXIF tag that says how to turn it. PaperPic shows the photo the way the tag says, as an `<img>` does, and the result of Apply comes out upright.
47
+
48
+ ## Know when it loads or fails
49
+
50
+ The [`load`](../reference/events#load) event reports that the image is on display, with its size. If the image cannot load, because it is missing, it is not an image or the browser cannot decode it, the viewer shows a message, and the [`error`](../reference/events#error) event carries `phase: 'load'`:
51
+
52
+ :::tabs key:framework
53
+ == JavaScript
54
+
55
+ ```ts
56
+ import { PaperPic } from '@paperpic/core'
57
+
58
+ const pic = new PaperPic(container, { src: '/documents/42.jpg', alt: 'Invoice 42' })
59
+
60
+ pic.on('load', ({ width, height }) => {
61
+ console.log(`The image is ${width}×${height} pixels`)
62
+ })
63
+ pic.on('error', ({ error, phase }) => {
64
+ if (phase === 'load') {
65
+ console.error(error.message)
66
+ }
67
+ })
68
+ ```
69
+
70
+ == Vue
71
+
72
+ ```vue
73
+ <script setup lang="ts">
74
+ import type { PaperPicEvents } from '@paperpic/vue'
75
+ import { PaperPic } from '@paperpic/vue'
76
+
77
+ function loaded({ width, height }: PaperPicEvents['load']) {
78
+ console.log(`The image is ${width}×${height} pixels`)
79
+ }
80
+
81
+ function failed({ error, phase }: PaperPicEvents['error']) {
82
+ if (phase === 'load') {
83
+ console.error(error.message)
84
+ }
85
+ }
86
+ </script>
87
+
88
+ <template>
89
+ <div style="height: 480px">
90
+ <PaperPic src="/documents/42.jpg" alt="Invoice 42" @load="loaded" @error="failed" />
91
+ </div>
92
+ </template>
93
+ ```
94
+
95
+ == React
96
+
97
+ ```tsx
98
+ import type { PaperPicEvents } from '@paperpic/react'
99
+ import { PaperPic } from '@paperpic/react'
100
+
101
+ function loaded({ width, height }: PaperPicEvents['load']) {
102
+ console.log(`The image is ${width}×${height} pixels`)
103
+ }
104
+
105
+ function failed({ error, phase }: PaperPicEvents['error']) {
106
+ if (phase === 'load') {
107
+ console.error(error.message)
108
+ }
109
+ }
110
+
111
+ export function Invoice() {
112
+ return (
113
+ <div style={{ height: 480 }}>
114
+ <PaperPic src="/documents/42.jpg" alt="Invoice 42" onLoad={loaded} onError={failed} />
115
+ </div>
116
+ )
117
+ }
118
+ ```
119
+
120
+ :::
121
+
122
+ The `status` of [`getState()`](../reference/state) gives the same answer at any time: `'empty'`, `'loading'`, `'ready'` or `'error'`.
123
+
124
+ ## Change or reload the image
125
+
126
+ - **A new `src`** loads the new image. While the user is editing, it discards the edits.
127
+ - **The same `src`** does nothing, so the result of Apply stays on display.
128
+ - **[`reload()`](../reference/methods#reload)** loads the current `src` again, which brings back the original after an Apply.
@@ -9,7 +9,7 @@ Phone photos have 12 megapixels or more, and editing them takes real work. This
9
9
 
10
10
  ## A Web Worker does the work
11
11
 
12
- Clean up and Straighten take more than a second on a 12-megapixel photo on a phone. On the main thread, the page would freeze for that long. PaperPic runs them in a Web Worker instead, so the page keeps responding while Apply runs.
12
+ Clean up and Straighten take about a second and a half on a 12-megapixel photo on a recent phone, as the [measured times](#measurements) show. On the main thread, the page would freeze for that long. PaperPic runs them in a Web Worker instead, so the page keeps responding while Apply runs.
13
13
 
14
14
  The worker ships inside the package and starts with the standard `new Worker(new URL(…, import.meta.url))`, which bundlers such as Vite and webpack 5 pick up on their own, with no configuration. If the worker cannot start, the editing runs on the main thread: it still works, but the page can freeze for a moment with large images.
15
15
 
@@ -19,6 +19,8 @@ With a Content Security Policy, allow:
19
19
 
20
20
  - `worker-src 'self'`, for the worker.
21
21
  - `img-src blob:`, because the viewer shows attached files and the results of Apply through `blob:` URLs.
22
+ - `paperpic` in `trusted-types`, if your policy restricts Trusted Types policies, because the icons of the buttons go through that policy.
23
+ - A `default` Trusted Types policy whose `createScriptURL` accepts the URL of the worker, if your policy requires Trusted Types. Bundlers only pick up a worker created from a plain URL, which Trusted Types block, so without that policy the editing runs on the main thread.
22
24
 
23
25
  ## Large photos
24
26
 
@@ -26,9 +28,21 @@ With a Content Security Policy, allow:
26
28
  - **On Apply**, every edit runs at full resolution. Large photos take a few seconds, so the viewer shows a message and blocks the controls meanwhile.
27
29
  - **To save time and memory**, set [`maxOutputSize`](../reference/options#maxoutputsize). A limit such as 2000 or 3000 pixels keeps documents readable, and makes Apply faster and the files smaller.
28
30
 
29
- ## Images it accepts
31
+ ## Measured times {#measurements}
30
32
 
31
- `src` takes a URL from the same origin as your page, or a `File` or `Blob` attached on the client. PaperPic reads the pixels of the image, and browsers only allow that for images from other origins under CORS, which PaperPic does not request. Serve the images from your own domain, or fetch them yourself and pass the `Blob`.
33
+ Each step of Apply, in the worker, on a Pixel 10 Pro with Chrome 156:
34
+
35
+ | Step | 2 MP | 12 MP | 37.5 MP |
36
+ | --------------------------- | ------ | ------ | ------- |
37
+ | Clean up | 256 ms | 1.5 s | 4.8 s |
38
+ | Straighten | 251 ms | 1.6 s | 5.0 s |
39
+ | Export to PNG | 92 ms | 378 ms | 979 ms |
40
+ | Export to JPEG, quality 0.9 | 33 ms | 142 ms | 525 ms |
41
+
42
+ - A move of the ruler of Clean up takes about 40 ms on the same phone, because it works on the preview of about 2 MP.
43
+ - A desktop computer with 8 cores does each step about six times faster.
44
+ - At 37.5 MP, Clean up needs about 340 MB of memory at its peak.
45
+ - Mid-range Android phones and iPhones are not measured yet.
32
46
 
33
47
  ## Server-side rendering
34
48
 
@@ -129,6 +129,12 @@ const pic = new PaperPic(container, {
129
129
 
130
130
  The preview while editing is always about 2 megapixels, so `maxOutputSize` changes only the result.
131
131
 
132
+ Safari on iOS limits a canvas to about 16 megapixels, and recent iPhones take photos of 24 megapixels or more, so Apply can fail at full resolution. If your users edit photos from an iPhone, set `maxOutputSize`. 3000 pixels keeps documents readable and stays well below the limit. [Apply fails with a large photo](./troubleshooting#too-large) shows the error.
133
+
134
+ ## Metadata {#metadata}
135
+
136
+ The result of Apply carries no metadata. PaperPic draws the image on a canvas, so the EXIF data of the photo, such as the GPS position, the camera and the date, is gone. The download button saves the source as it is until the first Apply, with its metadata.
137
+
132
138
  ## The download button
133
139
 
134
140
  [`download: true`](../reference/options#download) adds a button at the end of the toolbar that saves the image on display: the result of the last Apply, or else the source as it is. It is hidden while editing, because the edits are not applied yet. [`download()`](../reference/methods#download) does the same from code, with or without the button. The browser's context menu does not open over the viewer, so this button is the way to save the image from it.
@@ -55,6 +55,8 @@ Five [CSS tokens](../reference/css-tokens) set the surface, the text, the accent
55
55
  }
56
56
  ```
57
57
 
58
+ <Demo src="/samples/receipt.jpg" alt="A receipt" style="--paperpic-color-accent: #c2410c; --paperpic-radius: 0" />
59
+
58
60
  The tokens are inherited, so a class on the container of one viewer, or on the Vue or React component, changes that viewer only:
59
61
 
60
62
  ```css
@@ -7,6 +7,8 @@ description: How the Adjust tool of PaperPic changes the brightness and the cont
7
7
 
8
8
  Photos taken in poor light come out dark or gray. Adjust changes the brightness and the contrast and keeps the colors, for documents that should not become black and white, such as colored forms or photos.
9
9
 
10
+ <Demo src="/samples/receipt.jpg" alt="A receipt" :tools="['adjust']" />
11
+
10
12
  ## Use it
11
13
 
12
14
  1. Press Edit, then Adjust. Its panel takes the place of the tools: a ruler, and Brightness and Contrast to choose which tone it changes.
@@ -7,6 +7,8 @@ description: How the Crop tool of PaperPic keeps the part of a photo that holds
7
7
 
8
8
  A photo of a document often shows the table, a hand or other papers around it. Crop keeps the rectangle that holds the document and drops the rest.
9
9
 
10
+ <Demo src="/samples/receipt.jpg" alt="A receipt" :tools="['crop']" />
11
+
10
12
  ## Use it
11
13
 
12
14
  1. Press Edit, then Crop. A rectangle appears inside the image, with a handle at each corner.
@@ -7,6 +7,8 @@ description: How to rotate and flip a document image in PaperPic, in the edit mo
7
7
 
8
8
  Phones often save a photo of a document sideways or upside down, and some scans come out mirrored. Rotate left and Flip fix the orientation and leave the rest of the image as it is.
9
9
 
10
+ <Demo src="/samples/receipt.jpg" alt="A receipt" :tools="['rotate', 'flip']" />
11
+
10
12
  ## Rotate
11
13
 
12
14
  In the edit bar, Rotate left turns the image a quarter turn counterclockwise, as in photo galleries. Press it twice for a half turn, or three times for a quarter turn clockwise.
@@ -22,7 +24,7 @@ pic.rotate(-1)
22
24
 
23
25
  ## Flip
24
26
 
25
- Flip mirrors the image left to right, as it is on display, so after a quarter turn it still mirrors left to right on the screen. To turn an image upside down, flip it and rotate it twice.
27
+ Flip mirrors the image left to right, as it is on display, so after a quarter turn it still mirrors left to right on the screen. To mirror an image top to bottom, flip it and rotate it twice.
26
28
 
27
29
  Flips and rotations that cancel out leave nothing to apply. From code, call [`flip()`](../../reference/methods#flip).
28
30
 
@@ -0,0 +1,45 @@
1
+ ---
2
+ title: Troubleshooting
3
+ description: What to do when the PaperPic viewer has no height or no style, Tailwind CSS changes it, an image does not load or cannot be edited, the page freezes on Apply, or a large photo fails.
4
+ ---
5
+
6
+ # Troubleshooting
7
+
8
+ Most problems with PaperPic come from its setup, and not from the image. Find what you see, and the fix below it.
9
+
10
+ ## The viewer is a thin strip, or does not show {#no-height}
11
+
12
+ The viewer fills its container, and a container without a height collapses to the minimum height of the viewer. Give the container a height, such as `height: 480px`, or a place in a flex or grid layout that gives it one. [Styling](./styling) shows both.
13
+
14
+ ## The buttons have no style, and the console warns {#no-stylesheet}
15
+
16
+ The console says `PaperPic: the stylesheet is missing, so the viewer has no layout.` Import the stylesheet once in your app: `@paperpic/core/style.css`, or the `style.css` of `@paperpic/vue` or `@paperpic/react`.
17
+
18
+ ## Tailwind CSS removes the borders and the padding of the viewer {#tailwind}
19
+
20
+ The reset of Tailwind CSS 4 wins over the stylesheet of PaperPic when the cascade layers come in the wrong order. Name the layers before you import both, as [Styling](./styling#tailwind) shows.
21
+
22
+ ## The image shows, but editing it fails {#other-origin}
23
+
24
+ The [`error`](../reference/events#error) says that the image comes from another origin. Browsers do not let PaperPic read the pixels of such an image. Fetch it yourself and pass the `Blob`, as [Loading images](./loading#fetch) shows.
25
+
26
+ ## The image does not load {#load-error}
27
+
28
+ The viewer shows that the image could not be loaded, and `error` carries `phase: 'load'`. Check that the URL exists, and that the browser opens the format: HEIC only opens in Safari, and an SVG needs `width` and `height` attributes. [Loading images](./loading#formats) lists the formats.
29
+
30
+ ## The page freezes while Apply runs {#worker}
31
+
32
+ The worker did not start, so the editing runs on the main thread. It still works, but large photos freeze the page for a moment. The usual causes are:
33
+
34
+ - A Content Security Policy without `worker-src 'self'`, or one that requires Trusted Types without a `default` policy. [Performance and support](./performance) lists what to allow.
35
+ - The package loaded from a CDN, from another origin than the page. Browsers only start a worker from the origin of the page.
36
+
37
+ The network panel of the browser shows whether the page requested the worker file, whose name starts with `worker`.
38
+
39
+ ## Apply fails with a large photo {#too-large}
40
+
41
+ The `error` says `The browser could not read an image of …`. Browsers limit the size of a canvas, and Safari on iOS the most. Set [`maxOutputSize`](../reference/options#maxoutputsize), such as to 3000 pixels, which keeps documents readable.
42
+
43
+ ## The wheel zooms the image instead of scrolling the page {#wheel}
44
+
45
+ Set [`wheelZoom: false`](../reference/options#wheelzoom). The buttons, the keyboard and a pinch still zoom.
@@ -18,7 +18,7 @@ Small print and long receipts are hard to read at a glance on a screen. The view
18
18
  | Switch between the fit and 100% | Double click | Double tap | |
19
19
  | Fit the whole image | | | `0` |
20
20
 
21
- The keyboard works with the focus on the viewer. A pinch zooms around the point between the fingers. On a touch screen, one finger scrolls the page while the image is fitted, and pans the image once it is zoomed in.
21
+ The keyboard works with the focus on the viewer. While there is nothing to move, the arrow keys scroll the page. A pinch zooms around the point between the fingers. On a touch screen, one finger scrolls the page while the image is fitted, and pans the image once it is zoomed in.
22
22
 
23
23
  The zoom goes from the fit of the whole image, or 100% for a small image, up to 800%. An image that fits stays centered, and one that overflows pans up to its edges.
24
24
 
@@ -5,7 +5,7 @@ description: The events of PaperPic and what each one carries, load, error, chan
5
5
 
6
6
  # Events
7
7
 
8
- Events tell your code what happens in the viewer. Listen to them with [`on()`](./methods#on). In Vue they are component events, such as `@apply`, and in React they are props, such as `onApply`.
8
+ Events tell your code what happens in the viewer. Listen to them with [`on()`](./methods#on). In Vue they are component events, such as `@apply`, and in React they are props, such as `onApply`. A listener that throws does not stop the viewer: the page gets the error as any uncaught one, and the other listeners still run.
9
9
 
10
10
  :::tabs key:framework
11
11
  == JavaScript
@@ -36,15 +36,19 @@ The image is loaded and on display. `width` and `height` are its size in pixels.
36
36
 
37
37
  ## `error`
38
38
 
39
- - **Payload:** `{ error: Error }`
39
+ - **Payload:** `{ error: Error, phase: 'load' | 'preview' | 'apply' }`
40
40
 
41
- The image could not be loaded, or the edits could not be applied. After a failed Apply, the edit stays open.
41
+ Something failed, and `phase` says what:
42
+
43
+ - `'load'`: the image could not be loaded.
44
+ - `'preview'`: an edit could not be shown, as when the image is too large for the browser. The edit stays open.
45
+ - `'apply'`: the changes could not be applied. The edit stays open.
42
46
 
43
47
  ## `change`
44
48
 
45
49
  - **Payload:** [`PaperPicState`](./state)
46
50
 
47
- The user changed the view or the edit, such as by zooming, opening a tool or undoing. It also reports the start of Apply, with `busy: true`. `setOptions()` and the props of the components never emit it.
51
+ The user changed the view or the edit, such as by zooming, opening a tool or undoing. It also reports the start of Apply, with `busy: true`. Panning the image does not emit it, because the state does not hold its position. `setOptions()` and the props of the components never emit it.
48
52
 
49
53
  ## `apply`
50
54
 
@@ -27,7 +27,7 @@ class PaperPic {
27
27
 
28
28
  Creates the viewer inside `container`, which it fills. Give the container a height, or the viewer stays at its minimum height. [Options](./options) lists what `options` takes.
29
29
 
30
- It throws a `TypeError` if `container` is not an element. Create the viewer once the element exists, such as on mount.
30
+ It throws a `TypeError` if `container` is not an element. Create the viewer once the element exists, such as on mount. It throws a `RangeError` if an option is out of its range.
31
31
 
32
32
  ### `destroy()`
33
33
 
@@ -45,7 +45,7 @@ Removes the viewer and releases everything it holds, such as its worker and the
45
45
  function setOptions(options: PaperPicOptions): void
46
46
  ```
47
47
 
48
- Changes the options you pass and keeps the others. `undefined` brings an option back to its default. It never emits `change`, so two-way bindings do not loop.
48
+ Changes the options you pass and keeps the others. `undefined` brings an option back to its default. It never emits `change`, so two-way bindings do not loop. It throws a `RangeError` if an option is out of its range, and then no option changes.
49
49
 
50
50
  ### `getState()`
51
51
 
@@ -129,7 +129,7 @@ Turns the image a quarter turn: clockwise with `1`, the default, and countercloc
129
129
  function flip(): void
130
130
  ```
131
131
 
132
- Mirrors the image left to right as it is on display, so after a quarter turn it still mirrors left to right. To turn the image upside down, flip it and rotate it twice. It is an edit, and it does nothing outside the edit mode or while a tool is open.
132
+ Mirrors the image left to right as it is on display, so after a quarter turn it still mirrors left to right. To mirror it top to bottom, flip it and rotate it twice. It is an edit, and it does nothing outside the edit mode or while a tool is open.
133
133
 
134
134
  ### `openTool()`
135
135
 
@@ -13,7 +13,7 @@ const pic = new PaperPic(container, { src: '/receipt.jpg', alt: 'A receipt' })
13
13
  pic.setOptions({ editable: false })
14
14
  ```
15
15
 
16
- `setOptions()` changes only the options you pass, and `undefined` brings an option back to its default. It never emits `change`.
16
+ `setOptions()` changes only the options you pass, and `undefined` brings an option back to its default. It never emits `change`. An option out of its range throws a `RangeError` that names it, such as a `softness` of 2.
17
17
 
18
18
  ## Image
19
19
 
@@ -54,7 +54,7 @@ Whether to show the built-in toolbar and edit bar. Without them, build your own
54
54
  - **Type:** [`readonly ToolId[]`](./types#toolid)
55
55
  - **Default:** every tool
56
56
 
57
- The tools the edit bar offers. They keep the order of this table, whatever the order of the array.
57
+ The tools the edit bar offers. They keep the order of this table, whatever the order of the array. It only chooses the buttons: the [methods](./methods) work with every tool.
58
58
 
59
59
  | Id | Button |
60
60
  | --------------- | ----------------------------------- |
@@ -36,7 +36,7 @@ Every [option](./options) is a prop with the same name, such as `editable={false
36
36
  | `className` | `string` | Classes on top of `paperpic-host` |
37
37
  | `style` | `CSSProperties` | Inline styles |
38
38
 
39
- Objects and arrays, such as `labels` or `tools`, reach the viewer again whenever they are new. Define them outside the component, or with `useMemo`.
39
+ An object or array with the same contents as before, such as `tools={['crop', 'rotate']}`, changes nothing, so inline values are fine. A function is new on every render, so define the functions of `labels`, such as `zoomLevel`, outside the component, or build those labels with `useMemo`.
40
40
 
41
41
  ## Events
42
42
 
@@ -45,7 +45,7 @@ Objects and arrays, such as `labels` or `tools`, reach the viewer again whenever
45
45
  | `onApply` | [`ExportedImage`](./types#exportedimage) |
46
46
  | `onChange` | [`PaperPicState`](./state) |
47
47
  | `onDownload` | [`PaperPicDownload`](./types#paperpicdownload) |
48
- | `onError` | `{ error }` |
48
+ | `onError` | `{ error, phase }` |
49
49
  | `onLoad` | [`Size`](./types#size) |
50
50
 
51
51
  [Events](./events) describes each one. A new function does not recreate the viewer, so inline functions are fine. A change of props never calls `onChange`.
@@ -226,7 +226,7 @@ interface PaperPicEvents {
226
226
  apply: ExportedImage
227
227
  change: PaperPicState
228
228
  download: PaperPicDownload
229
- error: { error: Error }
229
+ error: { error: Error, phase: 'load' | 'preview' | 'apply' }
230
230
  load: Size
231
231
  }
232
232
  ```
@@ -31,7 +31,7 @@ The component fills its parent element, so give the parent a height.
31
31
 
32
32
  Every [option](./options) is a prop with the same name, such as `:editable="false"` or `:aspect-ratio="210 / 297"`. A change of a prop reaches the viewer through `setOptions()`.
33
33
 
34
- Objects and arrays that the template builds, such as `:labels="{ apply: t('apply') }"`, are new on every render of the parent, and the viewer receives them again each time. Build them with `computed` instead.
34
+ An object or array with the same contents as before, such as `:tools="['crop', 'rotate']"`, changes nothing, so the template can build them. A function is new on every render of the parent, so build `labels` that hold functions, such as `zoomLevel`, with `computed`.
35
35
 
36
36
  ## Events
37
37
 
@@ -40,7 +40,7 @@ Objects and arrays that the template builds, such as `:labels="{ apply: t('apply
40
40
  | `apply` | [`ExportedImage`](./types#exportedimage) |
41
41
  | `change` | [`PaperPicState`](./state) |
42
42
  | `download` | [`PaperPicDownload`](./types#paperpicdownload) |
43
- | `error` | `{ error }` |
43
+ | `error` | `{ error, phase }` |
44
44
  | `load` | [`Size`](./types#size) |
45
45
 
46
46
  [Events](./events) describes each one. A change of a prop never emits `change`.
package/dist/index.d.ts CHANGED
@@ -48,7 +48,7 @@ interface PaperPicProps {
48
48
  src?: PaperPicSource$1;
49
49
  /** Whether to show the built-in toolbar and edit bar. Without them, build your own with the methods of `instance`. */
50
50
  toolbar?: boolean;
51
- /** Which tools the edit bar offers. By default, all of them. */
51
+ /** Which tools the edit bar offers. By default, all of them. It only chooses the buttons: the methods work with every tool. */
52
52
  tools?: readonly ToolId$1[];
53
53
  /** Whether the wheel zooms. Turn it off when the viewer sits in a long page. */
54
54
  wheelZoom?: boolean;
@@ -61,6 +61,7 @@ declare const __VLS_export: import("vue").DefineComponent<PaperPicProps, {
61
61
  change: (payload: import("@paperpic/core").PaperPicState) => any;
62
62
  error: (payload: {
63
63
  error: Error;
64
+ phase: "load" | "preview" | "apply";
64
65
  }) => any;
65
66
  load: (payload: import("@paperpic/core").Size) => any;
66
67
  }, string, import("vue").PublicProps, Readonly<PaperPicProps> & Readonly<{
@@ -69,6 +70,7 @@ declare const __VLS_export: import("vue").DefineComponent<PaperPicProps, {
69
70
  onChange?: ((payload: import("@paperpic/core").PaperPicState) => any) | undefined;
70
71
  onError?: ((payload: {
71
72
  error: Error;
73
+ phase: "load" | "preview" | "apply";
72
74
  }) => any) | undefined;
73
75
  onLoad?: ((payload: import("@paperpic/core").Size) => any) | undefined;
74
76
  }>, {
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@paperpic/vue",
3
3
  "type": "module",
4
- "version": "0.2.0",
5
- "description": "Vue 3 components to view and edit document images with PaperPic.",
4
+ "version": "0.3.0",
5
+ "description": "Vue 3 component to view and edit document images with PaperPic: straighten, crop and clean up phone photos, scans and any image with text.",
6
6
  "author": "Marco Caparrós <hello@paperpic.dev>",
7
7
  "license": "MIT",
8
8
  "homepage": "https://paperpic.dev",
@@ -42,7 +42,7 @@
42
42
  "vue": "^3.5.0"
43
43
  },
44
44
  "dependencies": {
45
- "@paperpic/core": "0.2.0"
45
+ "@paperpic/core": "0.3.0"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@arethetypeswrong/core": "0.18.5",