-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathui.js
310 lines (245 loc) · 10.1 KB
/
ui.js
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
function addStyleToButton(button) {
button.style.cssText = 'border: 1px solid #ccc; border-radius: 4px; padding: 5px 10px; margin-right: 5px; margin-bottom: 5px;'
button.onmouseover = () => button.style.backgroundColor = '#eee'
button.onmouseout = () => button.style.backgroundColor = '#fff'
}
function createConfigModal() {
// Creates and displays a modal dialog to configure the completion API.
let modalBackground = document.createElement('div')
modalBackground.id = 'komple-config'
modalBackground.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 9999; display: none;'
// Clicking on the background sets display to none.
modalBackground.addEventListener('click', ({ target }) => {
target === modalBackground && ( modalBackground.style.display = 'none' )
})
let modal = document.createElement('div')
// Center-align the modal vertically and horizontally.
modal.style.cssText = 'position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; border-radius: 10px; z-index: 100000; padding: 20px; font-family: sans-serif;'
modalBackground.appendChild(modal)
let modalContent = document.createElement('div')
modalContent.classList.add('komple-config-content')
modal.appendChild(modalContent)
let modalHeader = document.createElement('div')
modalHeader.classList.add('komple-config-header')
modalContent.appendChild(modalHeader)
let modalTitle = document.createElement('h2')
modalTitle.textContent = 'Configure completion API'
modalHeader.appendChild(modalTitle)
// Create a button to copy settings to the clipboard.
let copyButton = document.createElement('button')
copyButton.textContent = 'Copy settings to clipboard'
copyButton.onclick = () => {
navigator.clipboard.writeText(JSON.stringify(settings, null, 2))
let oldText = copyButton.textContent
copyButton.textContent = 'Copied!'
setTimeout(() => copyButton.textContent = oldText, 1000)
}
addStyleToButton(copyButton)
modalHeader.appendChild(copyButton)
// Create a button to input settings from a window.prompt.
let inputButton = document.createElement('button')
inputButton.textContent = 'Input settings'
inputButton.onclick = () => {
let input = window.prompt('Paste settings (JSON) here:')
try {
Object.assign(settings, JSON.parse(input))
saveSettings()
createOptions()
createInputs()
inputButton.textContent = 'Input successful!'
setTimeout(() => inputButton.textContent = 'Input settings', 1000)
} catch (e) {
console.error(e)
inputButton.textContent = 'Input failed!'
setTimeout(() => inputButton.textContent = 'Input settings', 1000)
}
}
addStyleToButton(inputButton)
modalHeader.appendChild(inputButton)
let modalBody = document.createElement('div')
modalBody.classList.add('komple-config-body')
modalContent.appendChild(modalBody)
// Create a dropdown to select the api in settings.apis
let endpointSelect = document.createElement('select')
endpointSelect.id = 'komple-select-api'
endpointSelect.style.cssText = 'width: 100%;'
modalBody.appendChild(endpointSelect)
function createOptions() {
// Delete any existing options
endpointSelect.innerHTML = ''
for ( let api of settings.apis ) {
let option = document.createElement('option')
option.id = `komple-option-${api.name}`
option.textContent = api.name
option.selected = api == settings.api
endpointSelect.appendChild(option)
}
}
createOptions()
// If the user changes the selected API, update the settings.currentApiName and rerun the createInputs function.
endpointSelect.addEventListener('change', ({ target }) => {
settings.currentApiName = target.options[target.selectedIndex].textContent
createInputs()
})
// Add an empty span to anchor the inputs to.
let inputsAnchor = document.createElement('span')
modalBody.appendChild(inputsAnchor)
function createInputs() {
// First, delete the inputs table if it exists.
document.getElementById('komple-inputs-table')?.remove()
let inputsTable = document.createElement('table')
inputsTable.id = 'komple-inputs-table'
// Append the table to the anchor
inputsAnchor.appendChild(inputsTable)
let inputs = {}
let { api } = settings
for ( let key of [
'name', 'endpoint', 'auth', 'censor', 'promptKey', 'suffixKey', 'otherBodyParams', 'arrayKey', 'resultKey'
] ) {
let multiline = ['otherBodyParams'].includes(key)
let input = document.createElement(
multiline ? 'textarea' : 'input'
)
// If text area, set number of rows to the number of lines in the value.
multiline && ( input.rows = JSON.stringify(api[key], null, 2).split('\n').length )
!multiline && (
input.type =
['endpoint', 'auth'].includes(key) ?
api.censor ? 'password' : 'text'
: ['censor'].includes(key) ?
'checkbox'
: 'text'
)
let valueKey = input.type === 'checkbox' ? 'checked' : 'value'
input[valueKey] = key === 'otherBodyParams' ? JSON.stringify(api[key], null, 2) : api[key]
let tr = document.createElement('tr')
inputsTable.appendChild(tr)
let labelTd = document.createElement('td')
labelTd.textContent = {
name: 'Name',
endpoint: 'Endpoint',
auth: 'Authorization header',
promptKey: 'Prompt key',
suffixKey: 'Suffix key',
arrayKey: 'Array key',
resultKey: 'Result key',
otherBodyParams: 'Other body params',
censor: 'Censor endpoint \& key'
}[key]
let inputTd = document.createElement('td')
inputTd.appendChild(input)
tr.appendChild(labelTd)
tr.appendChild(inputTd)
let notes = {
name: 'Any name you want to use for this API.',
suffixKey: 'Leave empty if not supported.',
arrayKey: 'Leave empty if no array returned.',
auth: 'Include "Bearer", if applicable.',
}
for ( let noteKey in notes )
if ( noteKey === key ) {
let note = document.createElement('div')
note.style.cssText = 'font-size: 0.8em; color: #888; margin-bottom: 5px;'
note.textContent = notes[noteKey]
labelTd.appendChild(note)
}
input.addEventListener('change', () => {
if ( ['otherBodyParams'].includes(key) ) {
try {
api[key] = JSON.parse(input.value)
} catch (e) {
alert('Invalid JSON; reverting to previous value.')
input.value = JSON.stringify(api[key], null, 2)
return
}
} else {
key === 'censor' && (
['endpoint', 'auth'].forEach(key => {
inputs[key].type = input.checked ? 'password' : 'text'
})
)
if ( key === 'name' ) {
// Convert to lowercase and replace any non-alphanumeric characters with a dash. Update the input.
input.value = input.value.toLowerCase().replace(/[^a-z0-9]+/gi, '-')
if ( api !== settings.api ) {
if ( settings.apis.find(({ name }) => name === input.value) ) {
alert('Name already taken; reverting to previous value.')
input.value = api.name
return
}
} else {
settings.currentApiName = input.value
}
// Change the respective option in the dropdown.
let option = document.getElementById(`komple-option-${api.name}`)
option.textContent = input.value
option.id = `komple-option-${input.value}`
}
api[key] = input[valueKey]
}
saveSettings()
})
inputs[key] = input
}
}
createInputs()
let modalFooter = document.createElement('div')
modalFooter.classList.add('komple-config-footer')
modalContent.appendChild(modalFooter)
let buttonDiv = document.createElement('div')
buttonDiv.classList.add('komple-config-buttons')
// Align right with margins and paddings as needed
buttonDiv.style.cssText = 'display: flex; justify-content: flex-end; margin-top: 10px; margin-bottom: 10px;'
let buttonActions = ({
Clone() {
let newApi = {
...JSON.parse(JSON.stringify(settings.api)),
otherBodyParams: JSON.parse(JSON.stringify(settings.api.otherBodyParams)),
name: `${settings.api.name}-clone`
}
settings.apis.push(newApi)
settings.currentApiName = newApi.name
},
Delete() {
if ( settings.apis.length === 1 ) {
alert('You must have at least one API.')
return
}
settings.apis = settings.apis.filter(({ name }) => name !== settings.currentApiName)
settings.currentApiName = settings.apis[settings.apis.length - 1].name
},
Nudge() {
// Move up
let index = settings.apis.findIndex(({ name }) => name === settings.currentApiName)
if ( index === 0 ) return
let previousIndex = index - 1
let previousApi = settings.apis[previousIndex]
settings.apis[previousIndex] = settings.apis[index]
settings.apis[index] = previousApi
}
})
for ( let caption in buttonActions ) {
let action = buttonActions[caption]
let button = document.createElement('button')
button.textContent = caption
button.id = `komple-config-button-${caption.toLowerCase()}`
button.addEventListener('click', () => {
action()
createOptions()
createInputs()
saveSettings()
})
addStyleToButton(button)
buttonDiv.appendChild(button)
}
modalFooter.appendChild(buttonDiv)
// Add a 'buy me a beer' link on the right
let buyMeABeer = document.createElement('a')
buyMeABeer.href = 'https://vzakharov.github.io/buy-me-a-beer'
buyMeABeer.target = '_blank'
buyMeABeer.textContent = 'Buy me a 🍺'
buyMeABeer.style.cssText = 'margin-top: 10px; text-decoration: none; color: #888; float: right;'
modalFooter.appendChild(buyMeABeer)
document.body.appendChild(modalBackground)
return modalBackground
}