Index.svelte 1.75 KB
Newer Older
1
<script>
2
  import Router from 'svelte-spa-router'
3
  import Navigation from './Navigation.svelte'
4
  import { routes } from './sections'
5

Aral Balkan's avatar
Aral Balkan committed
6
  import { onMount, getContext } from 'svelte'
7
  import { get } from 'svelte/store'
Aral Balkan's avatar
Aral Balkan committed
8

9
  import { initialiseContext, state, signedIn} from './state.js'
Aral Balkan's avatar
Aral Balkan committed
10

11
12
  // Initialise state.
  initialiseContext()
13
14
15
16
  const { publicSocket, privateToken, privateSocket, privateMessages } = getContext(state)

  // Normal closure code for web sockets.
  const NORMAL_CLOSURE = 1000
Aral Balkan's avatar
Aral Balkan committed
17
18
19
20
21

  onMount(() => {
    // Make the public socket connection.
    $publicSocket = new WebSocket(`wss://${location.hostname}/public`)
    $publicSocket.onmessage = message => {
22
      console.log(`Public message: ${message.data}`)
Aral Balkan's avatar
Aral Balkan committed
23
    }
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

    // When signed in, make the private socket connection.
    signedIn.subscribe(isSignedIn => {
      if (isSignedIn) {
        console.log('Attempting to connect using private token', get(privateToken))

        // Create a web socket connection.
        $privateSocket = new WebSocket(`wss://${location.hostname}/private/${get(privateToken)}`)
        $privateSocket.onmessage = message => {
          $privateMessages = [...$privateMessages, message]
        }
      } else {
        if ($privateSocket !== null) {
          if ($privateSocket.readyState === 0 || $privateSocket.readyState === 1) {
            console.log('Signed out, closing private socket.')
            $privateSocket.send('Client is about to close.')
            $privateSocket.close(NORMAL_CLOSURE, 'Person signed out.')
            $privateToken = null
            $privateMessages = []
          }
        }
      }
    })
Aral Balkan's avatar
Aral Balkan committed
47
  })
48
49
50
51
52
53
</script>

<style>
  main { position: relative; }
</style>

Aral Balkan's avatar
Aral Balkan committed
54
<h1>Small Web Reference Client (Henry)</h1>
55
56
57
58

<Navigation />

<main>
59
  <Router {routes}/>
60
</main>