Skip to content

Edit in a dialog ​

Many apps edit a document in a dialog over the page, such as from a list of attachments. This example opens the viewer in a <dialog>, starts the edit mode, and closes the dialog when the user applies the changes or cancels them.

upload is the function from Upload to a server.

html
<button id="open" type="button">Edit the photo</button>
<dialog id="editor">
  <div id="viewer" style="width: min(90vw, 720px); height: 70vh"></div>
</dialog>
ts
import { PaperPic } from '@paperpic/core'
import '@paperpic/core/style.css'

const dialog = document.querySelector<HTMLDialogElement>('#editor')!
const pic = new PaperPic(document.querySelector<HTMLElement>('#viewer')!, {
  src: '/receipt.jpg',
  alt: 'A receipt',
})
let editing = false

document.querySelector('#open')!.addEventListener('click', () => {
  dialog.showModal()
  pic.edit()
})

// A photo still loading starts the edit once it is on display
pic.on('load', () => {
  if (dialog.open) {
    pic.edit()
  }
})

// Apply or Cancel ends the edit, and the dialog closes with it
pic.on('change', ({ mode }) => {
  if (editing && mode === 'view') {
    dialog.close()
  }
  editing = mode === 'edit'
})

// While editing, Esc goes to the viewer, which asks before discarding the changes
dialog.addEventListener('cancel', (event) => {
  if (editing) {
    event.preventDefault()
  }
})

pic.on('apply', ({ blob, type }) => upload(blob, type))

Notes ​

  • The viewer can live in the dialog while it is closed. It has no size then, and it fits the image as soon as the dialog opens.
  • Opening the dialog starts the edit mode. If the photo is still loading, the load event starts it instead.
  • Apply and Cancel end the edit, and the change that follows closes the dialog. If Apply fails, the edit stays open, and so does the dialog.
  • Each opening edits the image on display, which after an Apply is the result. To start from the original every time, call reload() before edit().

Released under the MIT License.