File size: 1,761 Bytes
2d8be8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<script>
  import * as clipboard from '@tauri-apps/plugin-clipboard-manager'
  import { open } from '@tauri-apps/plugin-dialog'
  import { arrayBufferToBase64 } from '../lib/utils'
  import { readFile } from '@tauri-apps/plugin-fs'

  export let onMessage
  export let insecureRenderHtml
  let text = 'clipboard message'

  function writeText() {
    clipboard
      .writeText(text)
      .then(() => {
        onMessage('Wrote to the clipboard')
      })
      .catch(onMessage)
  }

  async function writeImage() {
    try {
      const path = await open({
        title: 'Image to write to clipboard',
        filters: [
          {
            name: 'Clipboard IMG',
            extensions: ['png', 'jpg', 'jpeg']
          }
        ]
      })
      const bytes = await readFile(path)
      await clipboard.writeImage(bytes)
      onMessage('wrote image')
    } catch (e) {
      onMessage(e)
    }
  }

  async function read() {
    try {
      const image = await clipboard.readImage()
      arrayBufferToBase64(await image.rgba(), function (base64) {
        const src = 'data:image/png;base64,' + base64
        insecureRenderHtml('<img src="' + src + '"></img>')
      })
      return
    } catch (_) {}

    clipboard
      .readText()
      .then((contents) => {
        onMessage(`Clipboard contents: ${contents}`)
      })
      .catch((e) => {
        onMessage(e)
      })
  }
</script>

<div class="flex gap-1">
  <input
    class="grow input"
    placeholder="Text to write to the clipboard"
    bind:value={text}
  />
  <button class="btn" type="button" on:click={writeText}>Write</button>
  <button class="btn" type="button" on:click={writeImage}>Pick Image</button>
  <button class="btn" type="button" on:click={read}>Read</button>
</div>