Experiments >

Code animation: Copy & Paste

Experiment #16229th April, 2021by Joshua Nussbaum

For the event timeline, the user should be able to copy and paste events. I built an example for inserting using the context menu. This expands on that to add copy and paste menu items.

Clipboard API

The clipboard does not work in Svelte’s REPL because of permission restrictions, so I had to do it locally. This will prompt the user to allow copy and paste.

Code

Copying

async function copy() {
  if (!selected) return

  // convert selected item to blob
  // application/json is not supported :(
  const blob = new Blob([JSON.stringify(selected)], {type: 'text/plain'})

  // write the blob to the clipboard
  await navigator.clipboard.write([
    new ClipboardItem({[blob.type]: blob})
  ])
}

Pasting

async function paste() {
  // read from clipboard
  const items = await navigator.clipboard.read()

  // iterate thru clipboard items
  for (const item of items) {
    for (const type of item.types) {
      // find content type of `text/plain`
      if (type == "text/plain") {
        // get blob
        const blob = await item.getType(type)
        // get blob's text
        const text = await blob.text()

        try {
          // try to parse as JSON
          const event = JSON.parse(text)
          // publish event that we're inserting a duplicate at a new insertion point
          dispatch('add', {type: event.type, point: insertPoint})
        } catch (e) {}
      }
    }
  }
}

Demo

Notes

  • Support cut as well
  • Alternative is to not use system clipboard
view all experiments

Stay tuned in

Learn how to add more experimentation to your workflow