aboutsummaryrefslogtreecommitdiff
path: root/web/pw-server/src/lib/components/SubmitPane.svelte
blob: e46166cf0b991076481c4c0b5b8cc279b704386c (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<script lang="ts">
  import { ApiClient } from "$lib/api_client";

  import { get_session_token } from "$lib/auth";
  import { getBotName, saveBotName } from "$lib/bot_code";

  import { currentUser } from "$lib/stores/current_user";
  import { selectedOpponent, selectedMap } from "$lib/stores/editor_state";

  import { createEventDispatcher, onMount } from "svelte";
  import Select from "svelte-select";

  export let editSession;

  let availableBots: object[] = [];
  let maps: object[] = [];

  let botName: string | undefined = undefined;
  // whether to show the "save succesful" message
  let saveSuccesful = false;

  let saveErrors: string[] = [];

  onMount(async () => {
    botName = getBotName();
    const apiClient = new ApiClient();

    const [_bots, _maps] = await Promise.all([
      apiClient.get("/api/bots"),
      apiClient.get("/api/maps"),
    ]);

    availableBots = _bots;
    maps = _maps;

    if (!$selectedOpponent) {
      selectedOpponent.set(availableBots.find((b) => b["name"] === "simplebot"));
    }

    if (!$selectedMap) {
      selectedMap.set(maps.find((m) => m["name"] === "hex"));
    }
  });

  const dispatch = createEventDispatcher();

  async function submitBot() {
    let response = await fetch("/api/submit_bot", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        code: editSession.getDocument().getValue(),
        opponent_name: $selectedOpponent["name"],
        map_name: $selectedMap["name"],
      }),
    });

    let responseData = await response.json();

    if (response.ok) {
      // object has a "match" key containing the match data
      dispatch("matchCreated", responseData);
    } else {
      throw responseData;
    }
  }

  async function saveBot() {
    saveSuccesful = false;
    saveErrors = [];

    let response = await fetch("/api/save_bot", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${get_session_token()}`,
      },
      body: JSON.stringify({
        bot_name: botName,
        code: editSession.getDocument().getValue(),
      }),
    });

    let responseData = await response.json();
    if (response.ok) {
      dispatch("botSaved", responseData);
      saveBotName(botName);

      // make bot available in available bot list
      if (!availableBots.find((bot) => bot["id"] == responseData["id"])) {
        availableBots = [...availableBots, responseData];
      }
      saveSuccesful = true;
    } else {
      const error = responseData["error"];
      if (error["type"] === "validation_failed") {
        saveErrors = error["validation_errors"];
      } else if (error["type"] === "bot_name_taken") {
        saveErrors = ["Bot name is already taken"];
      } else {
        // unexpected error
        throw responseData;
      }
    }
  }
</script>

<div class="submit-pane">
  <div class="match-form">
    <h4>Play a match</h4>
    <div class="play-text">Opponent</div>
    <div class="opponent-select">
      <Select
        itemId="name"
        label="name"
        items={availableBots}
        bind:value={$selectedOpponent}
        clearable={false}
      />
    </div>
    <span>Map</span>
    <div class="map-select">
      <Select
        itemId="name"
        label="name"
        items={maps}
        bind:value={$selectedMap}
        clearable={false}
      />
    </div>
    <button class="submit-button play-button" on:click={submitBot}>Play</button>
  </div>
  <div class="save-form">
    <h4>Save your bot</h4>
    {#if $currentUser}
      <div>Add your bot to the opponents list</div>
      <input type="text" class="bot-name-input" placeholder="bot name" bind:value={botName} />
      {#if saveSuccesful}
        <div class="success-text">Bot saved succesfully</div>
      {:else if saveErrors.length > 0}
        <ul>
          {#each saveErrors as errorText}
            <li class="error-text">{errorText}</li>
          {/each}
        </ul>
      {/if}
      <button class="submit-button save-button" on:click={saveBot}>Save</button>
    {:else}
      Sign in to add your bot to the opponents list.
    {/if}
  </div>
</div>

<style lang="scss">
  .submit-pane {
    margin: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .submit-pane h4 {
    margin-bottom: 0.3em;
  }

  .opponent-select,
  .map-select {
    margin: 8px 0;
  }

  .save-form {
    margin-top: 8em;
  }

  .error-text {
    color: red;
  }

  .success-text {
    color: green;
    margin: 0 8px;
  }

  .submit-button {
    padding: 8px 16px;
    border-radius: 8px;
    border: 0;
    font-size: 18pt;
    display: block;
    margin: 10px auto;
    background-color: lightgreen;
    cursor: pointer;
  }

  .bot-name-input {
    width: 100%;
    font-size: 16px;
    padding: 8px 16px;
    box-sizing: border-box;
    margin: 10px 0;
    border: 1px solid rgb(216, 219, 223);
    border-radius: 3px;
  }
</style>