File size: 1,510 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
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

import WebSocket from 'tauri-plugin-websocket-api'
import './style.css'

let ws: WebSocket

document.addEventListener('DOMContentLoaded', async () => {
  document.querySelector('#send')?.addEventListener('click', send)
  document.querySelector('#disconnect')?.addEventListener('click', disconnect)
  await connect()
})

function _updateResponse(returnValue: unknown) {
  const msg = document.createElement('p')
  msg.textContent =
    typeof returnValue === 'string' ? returnValue : JSON.stringify(returnValue)
  document.querySelector('#response-container')?.appendChild(msg)
}

async function connect() {
  try {
    ws = await WebSocket.connect('ws://127.0.0.1:8080').then((r) => {
      _updateResponse('Connected')
      return r
    })
  } catch (e) {
    _updateResponse(e)
  }
  ws.addListener(_updateResponse)
}

function send() {
  ws.send(document.querySelector('#msg-input')?.textContent || '')
    .then(() => {
      _updateResponse('Message sent')
    })
    .catch(_updateResponse)
}

function disconnect() {
  ws.disconnect()
    .then(() => {
      _updateResponse('Disconnected')
    })
    .catch(_updateResponse)
}

document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
  <div>
    <input type="text" />
    <button id="send">send</button>
    <button id="disconnect">disconnect</button>
    <div id="response-container"></div>
  </div>
`