-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwith_api_select.tsx
85 lines (80 loc) · 2.8 KB
/
with_api_select.tsx
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
import { Component, ParentProps, createSignal, onMount } from "solid-js";
import { useApi } from "../contexts/ApiProvider";
import { ToastType, useToast } from "../contexts/ToastProvider";
import Api from "../core/api";
const WithApiSelect: Component<ParentProps> = (props) => {
const { apiDetails, setApiDetails } = useApi()
const { pushToast } = useToast()
const [apiUrl, setApiUrl] = createSignal(apiDetails().apiServer)
const [editMode, setEditMode] = createSignal(false)
const [loading, setLoading] = createSignal(false)
onMount(async () => {
if (apiDetails().info) return
setLoading(true)
let result = await new Api({ apiServer: apiUrl() }).getServerInfo()
setLoading(false)
if (result instanceof Error) {
setApiDetails({ authToken: undefined, info: undefined })
setEditMode(true)
pushToast({ message: "failed to validate compatible API server", type: ToastType.ERROR })
} else {
setApiDetails({ apiServer: apiUrl(), authToken: undefined, info: result })
}
})
const validateAPI = async () => {
setLoading(true)
let url = apiUrl().replace(/\/$/g, "")
let result = await new Api({ apiServer: url }).getServerInfo()
setLoading(false)
if (result instanceof Error) {
setApiDetails({ authToken: undefined, info: undefined })
pushToast({ message: "failed to validate compatible API server", type: ToastType.ERROR })
}
else {
setEditMode(false)
setApiDetails({ apiServer: url, authToken: undefined, info: result })
pushToast({ message: "set new API server", type: ToastType.SUCCESS })
}
}
return (
<>
<label class="form-control">
<span class="label"><span class="label-text">API Server</span></span>
<div class="join">
<input
value={apiUrl()}
oninput={(ev) => setApiUrl(ev.currentTarget.value)}
class="input input-sm w-full join-item"
classList={{
"input-bordered": editMode(),
}}
onkeydown={(ev) => { if (ev.key === "Enter" && editMode()) validateAPI() }}
type="url"
readonly={!editMode()}
placeholder="e.g. https://example.com/api"
required
/>
<button
onclick={() => {
if (editMode()) validateAPI()
else {
setApiDetails({ authToken: undefined, info: undefined })
setEditMode(true)
}
}}
class="btn btn-sm join-item"
classList={{
loading: loading(),
"btn-warning": editMode()
}}
type="button"
>
{editMode() && "Save" || "Edit"}
</button>
</div>
</label>
{props.children}
</>
)
}
export default WithApiSelect