-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEditScriptView.tsx
More file actions
263 lines (236 loc) · 7.68 KB
/
Copy pathEditScriptView.tsx
File metadata and controls
263 lines (236 loc) · 7.68 KB
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
import { useEffect, useState } from "react";
import { BadRequestErrorBodyCodec } from "@userscript-proxy/core/api/BadRequestErrorBody";
import { InternalServerErrorBodyCodec } from "@userscript-proxy/core/api/InternalServerErrorBody";
import {
ScriptDetailsCodec,
type ScriptDetails,
} from "@userscript-proxy/core/api/ScriptDetails";
import { ScriptNotFoundErrorBodyCodec } from "@userscript-proxy/core/api/ScriptNotFoundErrorBody";
import type { UpdateScriptRequest } from "@userscript-proxy/core/api/UpdateScriptRequest";
import { assertExhausted } from "@userscript-proxy/core/assertions";
import {
errorMessageFromCaught,
type ErrorInfo,
} from "@userscript-proxy/core/errors";
import { decodeJsonBody_NoReject } from "@userscript-proxy/core/fetching";
import type { NoRejectPromise } from "@userscript-proxy/core/promises";
import { Err, Ok, type Result } from "@userscript-proxy/core/results";
import { quote } from "@userscript-proxy/core/strings";
import { ScriptEditorView } from "./ScriptEditorView";
type EditScriptState =
| { tag: "Loading" }
| { tag: "Loaded"; content: string }
| { tag: "CouldNotLoad"; error: string };
type Props = {
filename: string;
onSaved: () => void;
onCancelled: () => void;
};
export function EditScriptView({ filename, onSaved, onCancelled }: Props) {
const [state, setState] = useState<EditScriptState>({ tag: "Loading" });
useEffect(() => {
void fetch(`/api/scripts/${encodeURIComponent(filename)}`)
.then((response) => interpretLoadResponse_NoReject(response))
.then((result) => {
switch (result.tag) {
case "Ok":
setState({ tag: "Loaded", content: result.value.scriptContent });
break;
case "Err":
console.error(result.error.logError);
setState({ tag: "CouldNotLoad", error: result.error.uiError });
break;
default:
assertExhausted(result, "load-script response interpretation");
}
})
.catch((caught: unknown) => {
setState({
tag: "CouldNotLoad",
error: `Unexpected error: ${errorMessageFromCaught(caught)}`,
});
});
}, [filename]);
switch (state.tag) {
case "Loading":
return (
<div className="modal-panel">
<p>Loading {filename} …</p>
</div>
);
case "CouldNotLoad":
return (
<div className="modal-panel">
<p>
Could not load <code>{filename}</code>. Reason:
<pre>{state.error}</pre>
</p>
<button className="button-secondary" onClick={onCancelled}>
Close
</button>
</div>
);
case "Loaded":
return (
<ScriptEditorView
filename={filename}
initialContent={state.content}
onSave_NoReject={(content) => update_NoReject(filename, content)}
onClose={onCancelled}
/>
);
default:
assertExhausted(state, "edit-script state");
}
async function update_NoReject(
filenameToSave: string,
content: string,
): NoRejectPromise<null, ErrorInfo> {
try {
const response = await fetch(
`/api/scripts/${encodeURIComponent(filenameToSave)}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
newScriptContent: content,
} satisfies UpdateScriptRequest),
},
);
const result = await interpretUpdateResponse_NoReject(response);
if (result.tag === "Ok") {
onSaved();
}
return result;
} catch (caught: unknown) {
const errorMsg = errorMessageFromCaught(caught);
return Err({
uiError: "Unexpected error.",
logError: `Unexpected error when updating script: ${errorMsg}`,
});
}
}
}
async function interpretLoadResponse_NoReject(
response: Response,
): Promise<Result<ScriptDetails, ErrorInfo>> {
if (response.ok) {
const decoded = await decodeJsonBody_NoReject(response, ScriptDetailsCodec);
if (decoded.tag === "Err") {
return Err({
uiError: "Could not load script.",
logError: `Could not load script. Reason: ${decoded.error}`,
});
}
return Ok(decoded.value);
}
const logMessagePrefix =
`Could not load script. Response status: ${response.status}.` as const;
switch (response.status) {
case 400: {
const bodyResult = await decodeJsonBody_NoReject(
response,
BadRequestErrorBodyCodec,
);
return Err({
uiError: "Invalid request.",
logError:
bodyResult.tag === "Ok"
? `${logMessagePrefix} Reason: ${bodyResult.value.badRequestReason}`
: `${logMessagePrefix} ${bodyResult.error}`,
});
}
case 404: {
const bodyResult = await decodeJsonBody_NoReject(
response,
ScriptNotFoundErrorBodyCodec,
);
return Err({
uiError:
bodyResult.tag === "Ok"
? `Script ${quote(bodyResult.value.missingScriptName)} not found.`
: "Script not found.",
logError:
bodyResult.tag === "Ok"
? `${logMessagePrefix} Script ${quote(bodyResult.value.missingScriptName)} not found.`
: `${logMessagePrefix} ${bodyResult.error}`,
});
}
case 500: {
const bodyResult = await decodeJsonBody_NoReject(
response,
InternalServerErrorBodyCodec,
);
return Err({
uiError: "Server failed to load script.",
logError:
bodyResult.tag === "Ok"
? `${logMessagePrefix} Reason: ${bodyResult.value.serverErrorReason}`
: `${logMessagePrefix} ${bodyResult.error}`,
});
}
default:
return Err({
uiError: "Could not load script.",
logError: `${logMessagePrefix} Server responded with ${response.status} ${response.statusText}.`,
});
}
}
async function interpretUpdateResponse_NoReject(
response: Response,
): NoRejectPromise<null, ErrorInfo> {
if (response.ok) {
return Ok(null);
}
const logMessagePrefix =
`Could not update script. Response status: ${response.status}.` as const;
switch (response.status) {
case 400: {
const bodyResult = await decodeJsonBody_NoReject(
response,
BadRequestErrorBodyCodec,
);
return Err({
uiError: "Invalid request.",
logError:
bodyResult.tag === "Ok"
? `${logMessagePrefix} Reason: ${bodyResult.value.badRequestReason}`
: `${logMessagePrefix} ${bodyResult.error}`,
});
}
case 404: {
const bodyResult = await decodeJsonBody_NoReject(
response,
ScriptNotFoundErrorBodyCodec,
);
return Err({
uiError:
bodyResult.tag === "Ok"
? `Script ${quote(bodyResult.value.missingScriptName)} not found on server.`
: "Script not found on server.",
logError:
bodyResult.tag === "Ok"
? `${logMessagePrefix} Filename: ${quote(bodyResult.value.missingScriptName)}`
: `${logMessagePrefix} ${bodyResult.error}`,
});
}
case 500: {
const bodyResult = await decodeJsonBody_NoReject(
response,
InternalServerErrorBodyCodec,
);
return Err({
uiError: "Server failed to update script.",
logError:
bodyResult.tag === "Ok"
? `${logMessagePrefix} Reason: ${bodyResult.value.serverErrorReason}`
: `${logMessagePrefix} ${bodyResult.error}`,
});
}
default:
return Err({
uiError: "Could not update script.",
logError: `${logMessagePrefix} Server responded with ${response.status} ${response.statusText}.`,
});
}
}